欧美国产另类久热|951超碰伊人久久|伊人影视久久久久|色婷婷亚洲小电影|色东京热69XX|婷婷玖玖深爱网|加勒比东京热网站|无码A级毛片在线观看|一级a毛一级a看|中文字幕人妻欧美

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

本文分享了Node.js寫文件的三種方式,具體內(nèi)容和如下

1、通過管道流寫文件

采用管道傳輸二進制流,可以實現(xiàn)自動管理流,可寫流不必當心可讀流流的過快而崩潰,適合大小文件傳輸(推薦)

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

 });

 // 當有數(shù)據(jù)可讀時,觸發(fā)該函數(shù),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 ');

 });

 // 數(shù)據(jù)讀取完畢

 readStream.on('end',function() {

   res.end();

 });

3、通過一次性讀完數(shù)據(jù)寫入

一次性讀取完文件所有內(nèi)容,適合小文件(不推薦)

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();

 });

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

更多信息請查看網(wǎng)絡編程
易賢網(wǎng)手機網(wǎng)站地址:三種Node.js寫文件的方式
關于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點

版權所有:易賢網(wǎng)