Node.js写文件的三种方法

博客搬家了,欢迎大家关注,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
 
posted @ 2016-03-07 18:02  猿客  Views(3673)  Comments(0Edit  收藏  举报