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
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM