Node.js readline 逐行讀取、寫入文件內(nèi)容的示例
本文介紹了運(yùn)用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)文章
前端+nodejs+mysql實現(xiàn)前后端聯(lián)通的完整代碼
Node.js主要屬于后端技術(shù),但也可以用于前端開發(fā)的某些場景,下面這篇文章主要介紹了前端+nodejs+mysql實現(xiàn)前后端聯(lián)通的完整代碼,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-04-04
Node.js Stream ondata觸發(fā)時機(jī)與順序的探索
今天小編就為大家分享一篇關(guān)于Node.js Stream ondata觸發(fā)時機(jī)與順序的探索,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03
node.js cookie-parser之parser.js
這篇文章主要介紹node.js cookie-parser之parser.js,講解的比較詳細(xì),需要的朋友可以參考下。2016-06-06
基于nodejs使用express創(chuàng)建web服務(wù)器的操作步驟
express實際上是對nodejs內(nèi)置http進(jìn)行封裝后的第三方包,其中提供了快捷創(chuàng)建web服務(wù)器以及處理請求路由的方法,使我們可以更加方便快捷的實現(xiàn)一個web服務(wù)器項目,本文件給大家詳細(xì)介紹基于nodejs使用express?創(chuàng)建web服務(wù)器的操作步驟2023-07-07
Node.js中多進(jìn)程模塊Cluster的介紹與使用
眾所周知Node.js是單線程的,一個單獨(dú)的Node.js進(jìn)程無法充分利用多核。Node.js從v0.6.0開始,新增cluster模塊,讓Node.js開發(fā)Web服務(wù)時,很方便的做到充分利用多核機(jī)器。這篇文章主要給大家介紹了關(guān)于Node.js中多進(jìn)程模塊Cluster的相關(guān)資料,需要的朋友可以參考下2017-05-05
如何在Nestjs和Vue3中使用socket.io示例詳解
這篇文章主要為大家介紹了如何在Nestjs和Vue3中使用socket.io示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08

