node常用模块

356 阅读4分钟

1. fs模块

1.1文件读取

(1)异步
fs.readFile(path[, options], callback)
  • 第一个参数为读取文件的路径;
  • 第二个参数为 encoding(编码,默认为 null),也可直接传入 encoding;例如("utf-8")
  • 第三个参数回调函数在读取文件成功后执行。没有返回值
(2)同步
fs.readFileSync(path[, options])
  • 第一个参数为读取文件的路径;
  • 第二个参数为 encoding(编码,默认为 null),也可直接传入 encoding;例如("utf-8")
  • 返回值为文件的内容,如果没有 encoding,返回的文件内容为 Buffer,如果有按照传入的编码解析。

1.2文件写入

(1)异步
fs.writeFile(file, data[, options], callback)
  • 第一个参数为读取文件的路径;
  • 第二个为写入内容
  • 第三个参数为 encoding(编码,默认为 null),也可直接传入 encoding;例如("utf-8")
  • 第四个参数回调函数在读取文件成功后执行。没有返回值
(2)同步
fs.writeFileSync(file, data[, options])
  • 第一个参数为读取文件的路径;
  • 第二个为写入内容
  • 第三个参数为 encoding(编码,默认为 null),也可直接传入 encoding;例如("utf-8") 。返回值为文件的内容

1.3 追加文件

(1)异步
fs.appendFile(file, data[, options], callback)
  • 第一个参数为读取文件的路径;
  • 第二个为写入内容
  • 第三个参数为 encoding(编码,默认为 null),也可直接传入 encoding;例如("utf-8") 。返回值为文件的内容
  • 第四个参数回调函数在文件追加写入数据成功后执行。
(2)同步
fs.appendFileSync(file, data[, options])
  • 第一个参数为读取文件的路径;
  • 第二个为写入内容
  • 第三个参数为 encoding(编码,默认为 null),也可直接传入 encoding;例如("utf-8") 。返回值为文件的内容

1.4 追加文件

fs.open(filename,flags,[mode],callback);

1.5追加文件

fs.read(fd, buffer, offset, length, position, callback((err, bytesRead, buffer)))

1.6写入文件

fs.write(fd, buffer[, offset[, length[, position]]], callback)

1.7关闭文件

fs.close(fd,[callback]);

1.8删除文件

fs.unlink(path, callback)

1.9截断文件

fs.ftruncate(fd[, len], callback)

2. Stream 流

2.1 可读流
let rs = fs.createReadStream(path,{
    flags: 'r', // 打开文件要做的操作,默认为'r'
    encoding: null, // 默认为null
    start: '0', // 开始读取的索引位置
    end: '', // 结束读取的索引位置(包括结束位置)
    highWaterMark: '', // 读取缓存区默认的大小的阀值64kb
})

2.2 写入流

var rs = fs.createWriteStream(path);

2.3 pipe 管道

readerStream.pipe(writerStream);

//链式流
fs.createReadStream('input.txt')
  .pipe(zlib.createGzip())
  .pipe(fs.createWriteStream('input.zip'));
2.4 方法及作用(状态)
// 1.监听data事件 流自动切换到流动模式
// 2.数据会尽可能快的读出
rs.on('data', function (data) {
    console.log(data);
});
// 数据读取完毕后触发end事件
rs.on('end', function () {
    console.log('读取完成');
});
// 可读流打开事件
rs.on('open', function () {
    console.log(err);
});
// 可读流关闭事件
rs.on('close', function () {
    console.log(err);
});
// 指定编码 和上面创建流时的参数encoding意思相同
rs.setEncoding('utf8');

rs.on('data', function (data) {
// 可读流暂停读取
    rs.pause();
    console.log(data);
});
setTimeout(function () {
// 可读流恢复读取
    rs.resume();
},2000);

3.url

3.1 parse

parse(urlStr,queryString,AnalysisHost)

//urlStr: 要解析的url地址
//queryString: 解析出来的查询字符串还是查询对象,true是对象 false是字符串
//AnalysisHost: 是否要解析出来host 

3.2 resolve

resolve(url,path)
//url: 解析时对应的基本的url path:要解析的超链接url

3.3 api

url.hash     //获取及设置 URL 的片段部分。
url.host     //获取及设置 URL 的主机部分。
url.hostname //获取及设置 URL 的主机名部分
url.href     //获取及设置序列化的 URL。
url.origin   //获取只读的序列化的 URL 的 origin。
url.password //获取及设置 URL 的密码部分。
url.pathname //获取及设置 URL 的路径部分。

4.http

4.1创建服务器

let http = require('http')
http.createServer((req, res) => {
    let buf = []
    res.writeHead(200,{
        "content-type":"text/plain"
    });
    req.on('data', data => {
        buf.push(data)
    })
    req.on('end', () => {
        let str = Buffer.concat(buf).toString()
        res.end(str)
    })
}).listen(3000, () => {
    console.log('serve')
})

//res.writeHead(statusCode,[heasers]):向请求的客户端发送响应头,该函数在一个请求中最多调用一次,如果不调用,则会自动生成一个响应头
//res.write(data,[encoding]):想请求的客户端发送相应内容,data是一个buffer或者字符串,如果data是字符串,则需要制定编码方式,默认为utf-8,在res.end调用之前可以多次调用
//res.end([data],[encoding]):结束响应,告知客户端所有发送已经结束,当所有要返回的内容发送完毕时,该函数必需被调用一次,两个可选参数与res.write()相同。如果不调用这个函数,客户端将用于处于等待状态。

4.2 get 请求

  var options={
      hostname:"cn.bing.com",
      port:8080
  }
  var req=http.request(options,function(res){
      res.setEncoding("utf-8");
      res.on("data",function(chunk){
          console.log(chunk.toString())
      });
      console.log(res.statusCode);
  });
  req.on("error",function(err){
      console.log(err.message);
  });
  req.end();

4.3 post 请求

  var http=require("http");
  var querystring=require("querystring");  // 因为node 不能解析post
  var postData=querystring.stringify({
      "content":"just a test",
      "mid":8837
  });
  var options={
      hostname:"www.imooc.com",
      port:80,
      path:"/course/document",
      method:"POST",
      headers:{
          "Accept":"application/json, text/javascript, */*; q=0.01",
          "Accept-Encoding":"gzip, deflate",
          "Accept-Language":"zh-CN,zh;q=0.8",
          "Connection":"keep-alive",
          "Content-Length":postData.length,
          "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
          "Host":"www.imooc.com",
          "Origin":"http://www.imooc.com",
          "Referer":"http://www.imooc.com/video/8837",
          "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2763.0 Safari/537.36",
          "X-Requested-With":"XMLHttpRequest",
      }
  }
  
  var req=http.request(options,function(res){
      res.on("data",function(chunk){
          console.log(chunk);
      });
      res.on("end",function(){
          console.log("### end ##");
      });
      console.log(res.statusCode);
  });
  
  req.on("error",function(err){
      console.log(err.message);
  })
  req.write(postData);
  req.end();