Node.js readline 逐行讀取、寫入文件內(nèi)容的示例
本文介紹了運用readline逐行讀取的兩種實現(xiàn),分享給大家,具體如下:
什么是Readline
Readline是Node.js里實現(xiàn)標(biāo)準(zhǔn)輸入輸出的封裝好的模塊,通過這個模塊我們可以以逐行的方式讀取數(shù)據(jù)流。使用require(“readline”)可以引用模塊。
效果圖如下:
左邊1.log 為源文件
右邊1.readline.log為復(fù)制后的文件
下邊為命令行輸出
實現(xiàn)方式一:
var readline = require('readline'); var fs = require('fs'); var os = require('os'); var fReadName = './1.log'; var fWriteName = './1.readline.log'; var fRead = fs.createReadStream(fReadName); var fWrite = fs.createWriteStream(fWriteName); var objReadline = readline.createInterface({ input: fRead, // 這是另一種復(fù)制方式,這樣on('line')里就不必再調(diào)用fWrite.write(line),當(dāng)只是純粹復(fù)制文件時推薦使用 // 但文件末尾會多算一次index計數(shù) sodino.com // output: fWrite, // terminal: true }); var index = 1; objReadline.on('line', (line)=>{ var tmp = 'line' + index.toString() + ':' + line; fWrite.write(tmp + os.EOL); // 下一行 console.log(index, line); index ++; }); objReadline.on('close', ()=>{ console.log('readline close...'); });
實現(xiàn)方式二:
var readline = require('readline'); var fs = require('fs'); var os = require('os'); var fReadName = './1.log'; var fWriteName = './1.readline.log'; var fRead = fs.createReadStream(fReadName); var fWrite = fs.createWriteStream(fWriteName); var enableWriteIndex = true; fRead.on('end', ()=>{ console.log('end'); enableWriteIndex = false; }); var objReadline = readline.createInterface({ input: fRead, output: fWrite, terminal: true }); var index = 1; fWrite.write('line' + index.toString() +':'); objReadline.on('line', (line)=>{ console.log(index, line); if (enableWriteIndex) { // 由于readline::output是先寫入后調(diào)用的on('line')事件, // 所以已經(jīng)讀取文件完畢時就不需要再寫行號了... sodino.com index ++; var tmp = 'line' + index.toString() + ':'; fWrite.write(tmp); } }); objReadline.on('close', ()=>{ console.log('readline close...'); });
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Node.js數(shù)據(jù)庫操作之查詢MySQL數(shù)據(jù)庫(二)
這篇文章主要介紹了Node.js數(shù)據(jù)庫操作之查詢MySQL數(shù)據(jù)庫的相關(guān)資料,文中介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用mysql能帶來一定的幫助,需要的朋友可以參考借鑒,下面來一起看看吧。2017-03-03Node中對非阻塞I/O、事件循環(huán)的知識點總結(jié)
在本篇文章里小編給大家整理的是一篇關(guān)于Node中對非阻塞I/O、事件循環(huán)的知識點分享內(nèi)容,需要的朋友們可以參考下。2020-01-01node.js使用net模塊創(chuàng)建服務(wù)器和客戶端示例【基于TCP協(xié)議】
這篇文章主要介紹了node.js使用net模塊創(chuàng)建服務(wù)器和客戶端,結(jié)合實例形式分析了node.js使用net模塊實現(xiàn)TCP客戶端與服務(wù)器端通信的相關(guān)操作技巧,需要的朋友可以參考下2020-02-02關(guān)于Error:EPERM:operation?not?permitted,mkdir...的幾種解決辦法對比
這篇文章主要給大家介紹了關(guān)于Error:EPERM:operation?not?permitted,mkdir...的幾種解決辦法對比,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2023-01-01