三種Node.js寫檔案的方式_node.js

來源:互聯網
上載者:User

本文分享了Node.js寫檔案的三種方式,具體內容和如下

1、通過管道流寫檔案
  採用管道傳輸二進位流,可以實現自動管理流,可寫流不必當心可讀流流的過快而崩潰,適合大小檔案傳輸(推薦)

var readStream = fs.createReadStream(decodeURIComponent(root + filepath.pathname)); // 必須解碼url readStream.pipe(res); // 管道傳輸 res.writeHead(200,{   'Content-Type' : contType }); // 出錯處理 readStream.on('error', function() {   res.writeHead(404,'can not find this page',{     'Content-Type' : 'text/html'   });   readStream.pause();   res.end('404 can not find this page');   console.log('error in writing or reading '); });

2、手動管理流寫入
  手動管理流,適合大小檔案的處理

var readStream = fs.createReadStream(decodeURIComponent(root + filepath.pathname)); res.writeHead(200,{   'Content-Type' : contType }); // 當有資料可讀時,觸發該函數,chunk為所讀取到的塊 readStream.on('data',function(chunk) {   res.write(chunk); }); // 出錯時的處理 readStream.on('error', function() {   res.writeHead(404,'can not find this page',{     'Content-Type' : 'text/html'   });   readStream.pause();   res.end('404 can not find this page');   console.log('error in writing or reading '); }); // 資料讀取完畢 readStream.on('end',function() {   res.end(); });

3、通過一次性讀完資料寫入
  一次性讀取完檔案所有內容,適合小檔案(不推薦)

fs.readFile(decodeURIComponent(root + filepath.pathname), function(err, data) {   if(err) {     res.writeHead(404,'can not find this page',{       'Content-Type' : 'text/html'     });     res.write('404 can not find this page');   }else {     res.writeHead(200,{       'Content-Type' : contType     });     res.write(data);   }   res.end(); });

以上就是本文的全部內容,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.