yuanke
博客搬家了,欢迎大家关注,https://bobjin.com

Node.js写文件的三种方式:

1、通过管道流写文件

  采用管道传输二进制流,可以实现自动管理流,可写流不必当心可读流流的过快而崩溃,适合大小文件传输(推荐)

 2  var readStream = fs.createReadStream(decodeURIComponent(root + filepath.pathname)); // 必须解码url
 3  readStream.pipe(res); // 管道传输
 4  res.writeHead(200,{
 5      \'Content-Type\' : contType
 6  });
 7 
 8  // 出错处理
 9  readStream.on(\'error\', function() {
10      res.writeHead(404,\'can not find this page\',{
11          \'Content-Type\' : \'text/html\'
12      });
13      readStream.pause();
14      res.end(\'404 can not find this page\');
15      console.log(\'error in writing or reading \');
16  });

2、手动管理流写入

  手动管理流,适合大小文件的处理

 1 var readStream = fs.createReadStream(decodeURIComponent(root + filepath.pathname));
 2  res.writeHead(200,{
 3      \'Content-Type\' : contType
 4  });
 5 
 6  // 当有数据可读时,触发该函数,chunk为所读取到的块
 7  readStream.on(\'data\',function(chunk) {
 8      res.write(chunk);
 9  });
10 
11  // 出错时的处理
12  readStream.on(\'error\', function() {
13      res.writeHead(404,\'can not find this page\',{
14          \'Content-Type\' : \'text/html\'
15      });
16      readStream.pause();
17      res.end(\'404 can not find this page\');
18      console.log(\'error in writing or reading \');
19  });
20 
21  // 数据读取完毕
22  readStream.on(\'end\',function() {
23      res.end();
24  });

3、通过一次性读完数据写入

  一次性读取完文件所有内容,适合小文件(不推荐)


 1 fs.readFile(decodeURIComponent(root + filepath.pathname), function(err, data) {
 2      if(err) {
 3          res.writeHead(404,\'can not find this page\',{
 4              \'Content-Type\' : \'text/html\'
 5          });
 6          res.write(\'404 can not find this page\');
 7 
 8      }else {
 9          res.writeHead(200,{
10              \'Content-Type\' : contType
11          });
12          res.write(data);
13      }
14      res.end();
15  });
博客搬家了,欢迎大家关注,https://bobjin.com
 

分类:

技术点:

相关文章:

  • 2021-11-07
  • 2021-11-23
  • 2020-12-22
  • 2021-09-20
  • 2021-11-20
  • 2021-09-16
  • 2021-09-21
  • 2021-07-27
猜你喜欢
  • 2021-09-05
  • 2021-10-13
  • 2021-10-13
  • 2021-06-21
  • 2021-09-07
  • 2021-11-03
相关资源
相似解决方案