最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

三種Node.js寫文件的方式

 更新時(shí)間:2016年03月08日 09:00:01   作者:猿客  
這篇文章主要為大家詳細(xì)介紹了三種Node.js寫文件的方式,感興趣的小伙伴們可以參考一下

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

1、通過(guò)管道流寫文件
  采用管道傳輸二進(jìn)制流,可以實(shí)現(xiàn)自動(dòng)管理流,可寫流不必當(dāng)心可讀流流的過(guò)快而崩潰,適合大小文件傳輸(推薦)

var readStream = fs.createReadStream(decodeURIComponent(root + filepath.pathname)); // 必須解碼url
 readStream.pipe(res); // 管道傳輸
 res.writeHead(200,{
   'Content-Type' : contType
 });

 // 出錯(cuò)處理
 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、手動(dòng)管理流寫入
  手動(dòng)管理流,適合大小文件的處理

var readStream = fs.createReadStream(decodeURIComponent(root + filepath.pathname));
 res.writeHead(200,{
   'Content-Type' : contType
 });

 // 當(dāng)有數(shù)據(jù)可讀時(shí),觸發(fā)該函數(shù),chunk為所讀取到的塊
 readStream.on('data',function(chunk) {
   res.write(chunk);
 });

 // 出錯(cuò)時(shí)的處理
 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、通過(guò)一次性讀完數(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();
 });

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評(píng)論

凤台县| 栾城县| 乐陵市| 天全县| 宕昌县| 湖北省| 曲松县| 大荔县| 陆良县| 洮南市| 图木舒克市| 紫云| 永宁县| 勐海县| 宁陵县| 浮山县| 三亚市| 杭州市| 花垣县| 嘉义县| 肥城市| 呼图壁县| 防城港市| 沁源县| 云梦县| 元谋县| 彰化县| 鹰潭市| 平罗县| 宽城| 库尔勒市| 临汾市| 抚州市| 县级市| 六安市| 宁乡县| 南川市| 深圳市| 济宁市| 苍梧县| 蒙阴县|