三種Node.js寫文件的方式
本文分享了Node.js寫文件的三種方式,具體內(nèi)容和如下
1、通過管道流寫文件
采用管道傳輸二進(jìn)制流,可以實(shí)現(xiàn)自動管理流,可寫流不必當(dāng)心可讀流流的過快而崩潰,適合大小文件傳輸(推薦)
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、手動管理流寫入
手動管理流,適合大小文件的處理
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、通過一次性讀完數(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)容,希望對大家的學(xué)習(xí)有所幫助。
- 淺談Node.js:fs文件系統(tǒng)模塊
- 基于node.js的fs核心模塊讀寫文件操作(實(shí)例講解)
- Node.js本地文件操作之文件拷貝與目錄遍歷的方法
- Node.js實(shí)現(xiàn)在目錄中查找某個(gè)字符串及所在文件
- Node.js 文件夾目錄結(jié)構(gòu)創(chuàng)建實(shí)例代碼
- Node.js查找當(dāng)前目錄下文件夾實(shí)例代碼
- Node.JS 循環(huán)遞歸復(fù)制文件夾目錄及其子文件夾下的所有文件
- Node.js文件操作詳解
- 在Node.js中實(shí)現(xiàn)文件復(fù)制的方法和實(shí)例
- node.js基于fs模塊對系統(tǒng)文件及目錄進(jìn)行讀寫操作的方法詳解
相關(guān)文章
node.js中的定時(shí)器nextTick()和setImmediate()區(qū)別分析
本文介紹了node.js中的定時(shí)器nextTick()和setImmediate()的區(qū)別分析,非常的不錯(cuò),這里推薦給大家。2014-11-11Node.js中的模塊機(jī)制學(xué)習(xí)筆記
這篇文章主要介紹了Node.js中的模塊機(jī)制學(xué)習(xí)筆記,本文講解了CommonJS模塊規(guī)范、Node模塊實(shí)現(xiàn)過程、模塊調(diào)用棧、包與NPM等內(nèi)容,需要的朋友可以參考下2014-11-11Node.js參數(shù)校驗(yàn)?zāi)Kminijoi使用詳解
這篇文章主要為大家介紹了Node.js參數(shù)校驗(yàn)?zāi)Kminijoi使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09Node升級后vue項(xiàng)目node-sass報(bào)錯(cuò)問題及解決
這篇文章主要介紹了Node升級后vue項(xiàng)目node-sass報(bào)錯(cuò)問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03