Node.js readline 逐行讀取、寫入檔案內容的樣本,node.jsreadline
本文介紹了運用readline逐行讀取的兩種實現,分享給大家,具體如下:
什麼是Readline
Readline是Node.js裡實現標準輸入輸出的封裝好的模組,通過這個模組我們可以以逐行的方式讀取資料流。使用require(“readline”)可以引用模組。
如下:
左邊1.log 為源檔案
右邊1.readline.log為複製後的檔案
下邊為命令列輸出
實現方式一:
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, // 這是另一種複製方式,這樣on('line')裡就不必再調用fWrite.write(line),當只是純粹複製檔案時推薦使用 // 但檔案末尾會多算一次index計數 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...'); });
實現方式二:
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是先寫入後調用的on('line')事件, // 所以已經讀取檔案完畢時就不需要再寫行號了... sodino.com index ++; var tmp = 'line' + index.toString() + ':'; fWrite.write(tmp); } }); objReadline.on('close', ()=>{ console.log('readline close...'); });
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。