金秋韵 發表於 2023-3-16 14:06:00

Node.js

<h1 id="1node常用命令">1.Node常用命令</h1>
<p>↑箭头快速定位到上一条命令</p>
<p>tab键快速补全文件路径</p>
<p>使用esc键快速清空命令</p>
<p>使用cls命令可以清空终端</p>
<h1 id="2fs文件系统模块">2.fs文件系统模块</h1>
<p>fs模块是Node.js官方提供的用来操作文件的模块,它提供了一系列的方法和属性,用来满足用户对文件的操作需求</p>
<p>fs.readFile()方法,用来读取指定文件中的内容</p>
<p>fs.writeFile()方法,用来向指定的文件中写入内容</p>
<p>如果要使用 要先导入fs模块</p>
<p>eg:const fs=require('fs');</p>
<h2 id="21fsreadfile的语法格式">2.1fs.readFile()的语法格式</h2>
<pre><code class="language-js">//1.导入fs模块
const fs = require('fs');

//2.调用fs.readFile()方法读取文件
//参数1:读取文件的存放路径
//参数2:读取文件时候采用的编码格式,一般默认指定utf8
//参数3:回调函数,拿到读取失败和成功的结果 err dataStr
fs.readFile('./files/11.txt', 'utf8', function(err, dataStr) {
    console.log(err);
    //如果读取成功则err的值为null
    //如果读取失败则err的值为错误对象 dataStr的值为undefined
    console.log('***********');
    console.log(dataStr);
})
</code></pre>
<p>判断文件是否读取成功</p>
<pre><code class="language-js">const fs = require('fs');
fs.readFile('./files/1.txt', 'utf8', function(err, dataStr) {
    if (err) {
      return console.log('读取文件失败!' + err.message);
    }
    console.log('读取文件成功' + dataStr);
})
</code></pre>
<h2 id="22fswritefile">2.2fs.writeFile()</h2>
<p>注意:fs.writeFile()方法只能用来创建文件,不能用来创建路径</p>
<p>重复调用的话新内容会覆盖旧内容</p>
<pre><code class="language-js">const fs = require('fs');
//参数1:表示文件的存放路径
//参数2:表示要写入的内容
//参数3:回调函数
fs.writeFile('f:./files/2.txt', 'abcd', function(err) {
    //如果文件写入成功,则err的值为null
    //如果文件写入失败,则err的值为一个错误对象
    console.log(err);
})
</code></pre>
<pre><code class="language-js">const fs = require('fs');
//参数1:表示文件的存放路径
//参数2:表示要写入的内容
//参数3:回调函数
fs.writeFile('./files/3.txt', 'abcd', function(err) {
    //如果文件写入成功,则err的值为null
    //如果文件写入失败,则err的值为一个错误对象
    // console.log(err);
    if (err) {
      return console.log(('文件写入失败' + err.message));
    }
    console.log('文件写入成功');
})
</code></pre>
<h2 id="23fs模块-路径动态拼接的问题">2.3fs模块 路径动态拼接的问题</h2>
<p>——dirname表示当前文件所处的目录</p>
<pre><code class="language-js">//__dirname表示当前文件所处的目录
const fs = require('fs');
fs.readFile(__dirname + '/files/1.txt', 'utf8', function(err, dataStr) {
    if (err) {
      return console.log('读取文件错误!' + err.message);
    }
    console.log(dataStr);
})
</code></pre>
<h1 id="3path路径模块">3.path路径模块</h1>
<p>path.join()方法用来将多个路径片段拼接成一个完成的路径字符串</p>
<p>paht.basenname()方法,用来从路径字符串中,将文件名解析出来</p>
<p>导入:</p>
<p>const path=require(‘path);</p>
<p>path.join()方法用来将多个路径片段拼接成一个完成的路径字符串</p>
<pre><code class="language-js">const path = require('path');
const fs = require('fs');
//注意 ../会抵消前面的路径
const pathstr = path.join('/a', '/b/c', '../', '/d', 'e');
console.log(pathstr);
// fs.readFile(path.join(__dirname, './files/1.txt'), 'utf8', function(err, dataStr) {
//   if (err) {
//         return console.log(err.message);
//   }
//   console.log(dataStr);
// })
</code></pre>
<p>paht.basenname()方法,用来从路径字符串中,将文件名解析出来</p>
<pre><code class="language-js">const path = require('path');
//定义文件的存放路径
const fpath = '/a/b/c/index.html';
// const fullname = path.basename(fpath);
// console.log(fullname);//index.html
const nameWithout = path.basename(fpath, '.html');
console.log(nameWithout);//index
</code></pre>
<p>path.extname()可以获取路径中的扩展名部分</p>
<pre><code class="language-js">const path = require('path');
//定义文件的存放路径
const fpath = '/a/b/c/index.html';
const fext = path.extname(fpath);
console.log(fext);//.html
</code></pre>
<h1 id="4http模块">4.http模块</h1>
<p>const http=require('http');</p>
<p>创建基本web服务器</p>
<pre><code class="language-js">//1.导入http模块
const http = require('http');
//2.创建web服务器实例
const server = http.createServer();
//3.为服务器实例绑定request事件,监听客户端的请求
server.on('request', function(req, res) {
      console.log('Someone visit our web sever.');
    })
    //4.启动服务器
server.listen(80, function() {
    console.log('server running at http://127.0.0.1');
})
</code></pre>
<h2 id="41reg请求对象">4.1reg请求对象</h2>
<p>只要服务器接收到了客户端的请求,就会调用通过server.on()为服务器绑定的request事件处理函数,如果想在事件处理函数中访问与客户端的数据或属性,可以使用如下方式</p>
<pre><code class="language-js">const req = require('express/lib/request');
const http = require('http');
const server = http.createServer();
//req是请求对象,包含了与客户端相关的数据和属性
server.on('request', (req) =&gt; {
    //req.url是客户端请求的url地址
    const url = req.url;
    //req.method是客户端请求的method类型
    const method = req.method;
    const str = `Your request url is ${url},and rquest method is ${method}`;
    console.log(str);
});




server.listen(80, () =&gt; {
    console.log('server running at http://127.0.0.1');
})
</code></pre>
<h2 id="42res响应对象">4.2res响应对象</h2>
<p>在服务器的request事件处理函数中,如果想访问与服务器相关的数据或属性,可以使用如下的方式</p>
<pre><code class="language-js">const req = require('express/lib/request');
const http = require('http');
const server = http.createServer();
//req是请求对象,包含了与客户端相关的数据和属性
server.on('request', (req, res) =&gt; {
    //req.url是客户端请求的url地址
    const url = req.url;
    //req.method是客户端请求的method类型
    const method = req.method;
    const str = `Your request url is ${url},and rquest method is ${method}`;
    console.log(str);
    //调用res.end()方法,向客户端响应一些内容
    res.end(str);
});

</code></pre>
<h2 id="43解决中文乱码问题">4.3解决中文乱码问题</h2>
<pre><code class="language-js">const http = require('http');
const server = http.createServer();
server.on('request', (req, res) =&gt; {
    const url = req.url;
    const method = req.method;
    const str = `您请求的URL地址是${url},请求的mthode类型是 ${method}`;
    //调用res.setHeader()方法,设置Content-Type响应头,解决中文乱码问题
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    res.end(str);
})
server.listen(80, () =&gt; {
    console.log('server running at http://127.0.0.1');
})
</code></pre>
<h2 id="44根据不同的url响应不同的html内容">4.4根据不同的url响应不同的html内容</h2>
<pre><code class="language-js">const req = require('express/lib/request');
const res = require('express/lib/response');
const http = require('http');
const server = http.createServer();
server.on('request', (req, res) =&gt; {
    //1.获取请求的url地址
    const url = req.url;
    //2.设置默认的响应内容为404 Not found
    let content = '&lt;h1&gt;404 Not found!&lt;/h1&gt;';
    //3.判断用户请求的是否为/或index.html首页
    if (url === '/' || url === '/index.html') {
      content = '&lt;h1&gt;首页&lt;/h1&gt;'
    } else if (url === '/about.html') {
      content = '&lt;h1&gt;关于页面&lt;/h1&gt;'
    }

    //4.判断用户请求的是否为/about.html页面

    //5.设置响应头,防止乱码
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
      //6.使用res.end()把内容响应给客户端
    res.end(content);
});


server.listen(80, () =&gt; {
    console.log('server running at http://127.0.0.1');
})
</code></pre>
<h1 id="5综合时钟案例">5.综合时钟案例</h1>
<pre><code class="language-js">//1.导入http模块
const http = require('http');
//1.2导入fs模块
const fs = require('fs');
//1.3导入path模块
const path = require('path');

//2.1创建web服务器
const server = http.createServer();
//2.2监听web服务器的request事件
server.on('request', (req, res) =&gt; {
    //3.1获取到客户端请求的url地址
    const url = req.url;
    //3.2把请求的url地址映射为具体文件的存放路径
    // const fpath = path.join(__dirname, url)
    //5.1预定一个空白的文件存放路径
    let fpath = '';
    if (url === '/') {
      fpath = path.join(__dirname, '/clock/index.html')
    } else {
      fpath = path.join(__dirname, '/clock', url);
    }
    //4.1根据映射过来的文件路径读取文件内容
    fs.readFile(fpath, 'utf-8', (err, dataStr) =&gt; {
      //4.2读取失败,向客户端响应固定错误消息
      if (err) return res.end('404 Not found!')
            //4.3读取成功,将读取成功的内容,响应给客户端
      res.end(dataStr);
    })
})


//2.3启动服务器
server.listen(80, function() {
    console.log('server is running at http://127.0.0.1');
})
</code></pre>
<h1 id="6require方法">6.require()方法</h1>
<p>使用require()方法加载其他模块时,会执行被加载模块中的代码</p>
<p>注意“在使用require加载用户自定义模块期间可以省略.js后缀名</p>
<h1 id="7模块作用域">7.模块作用域</h1>
<ul>
<li>和函数作用域类似,在自定义模块中定义的变量、方法等成员,只能在当前模块内被访问,这种模块级别的访问限制,叫做模块作用域</li>
<li>防止全局变量污染</li>
</ul>
<h1 id="8向外共享模块作用域中的成员">8.向外共享模块作用域中的成员</h1>
<ul>
<li>自定义模块中都有一个 <code>module</code> 对象,存储了和当前模块有关的信息</li>
<li>在自定义模块中,可以使用 <code>module.exports</code> 对象,将模块内的成员共享出去,供外界使用。导入自定义模块时,得到的就是 <code>module.exports</code> 指向的对象。</li>
<li>默认情况下,<code>exports</code> 和 <code>module.exports</code> 指向同一个对象。最终共享的结果,以 <code>module.exports</code> 指向的对象为准。</li>
</ul>
<h2 id="81moduleexports对象">8.1module.exports对象</h2>
<p>在一个自定义模块中,默认情况下module.exports={};</p>
<h1 id="9模块化规范">9.模块化规范</h1>
<ul>
<li>每个模块内部,<code>module</code> 变量代表当前模块</li>
<li><code>module</code> 变量是一个对象,<code>module.exports</code> 是对外的接口</li>
<li>加载某个模块即加载该模块的 <code>module.exports</code> 属性</li>
</ul>
<h3 id="_"></h3>
<h1 id="10npm和包">10.npm和包</h1>
<p>包:第三方模块叫做包</p>
<p>包是基于内置模块封装出来的</p><br><br>
来源:https://www.cnblogs.com/luckily7/p/17222349.html
頁: [1]
查看完整版本: Node.js