三種Node.js寫文件的方式
來源:易賢網 閱讀:899 次 日期:2016-07-22 15:38:38
溫馨提示:易賢網小編為您整理了“三種Node.js寫文件的方式”,方便廣大網友查閱!

本文分享了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();

 });

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

更多信息請查看網絡編程
易賢網手機網站地址:三種Node.js寫文件的方式
由于各方面情況的不斷調整與變化,易賢網提供的所有考試信息和咨詢回復僅供參考,敬請考生以權威部門公布的正式信息和咨詢為準!

2026國考·省考課程試聽報名

  • 報班類型
  • 姓名
  • 手機號
  • 驗證碼
關于我們 | 聯系我們 | 人才招聘 | 網站聲明 | 網站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點 | 投訴建議
工業和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網安備53010202001879號 人力資源服務許可證:(云)人服證字(2023)第0102001523號
云南網警備案專用圖標
聯系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關注公眾號:hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權所有:易賢網
云南網警報警專用圖標
未满十八18勿进黄网站免费看