本文介紹了運(yùn)用readline逐行讀取的兩種實(shí)現(xiàn),分享給大家,具體如下:
什么是Readline
Readline是Node.js里實(shí)現(xiàn)標(biāo)準(zhǔn)輸入輸出的封裝好的模塊,通過這個(gè)模塊我們可以以逐行的方式讀取數(shù)據(jù)流。使用require(“readline”)可以引用模塊。
效果圖如下:
左邊1.log 為源文件
右邊1.readline.log為復(fù)制后的文件
下邊為命令行輸出
實(shí)現(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ù)制文件時(shí)推薦使用 // 但文件末尾會(huì)多算一次index計(jì)數(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...'); });
實(shí)現(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)讀取文件完畢時(shí)就不需要再寫行號(hào)了... sodino.com index ++; var tmp = 'line' + index.toString() + ':'; fWrite.write(tmp); } }); objReadline.on('close', ()=>{ console.log('readline close...'); });
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com