国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

三種Node.js寫文件的方式

2019-11-20 10:26:06
字體:
來源:轉載
供稿:網友

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

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 辰溪县| 民勤县| 宜阳县| 定日县| 泽州县| 云霄县| 澄江县| 东城区| 土默特左旗| 静安区| 册亨县| 抚松县| 安塞县| 磴口县| 泰和县| 三门县| 岳阳县| 建阳市| 元江| 兴业县| 汨罗市| 嘉峪关市| 乌鲁木齐县| 房山区| 汨罗市| 贵港市| 湾仔区| 沁源县| 武邑县| 泰安市| 澄迈县| 禹州市| 安西县| 高阳县| 五大连池市| 丰原市| 额尔古纳市| 喀什市| 江源县| 仙居县| 包头市|