您的当前位置:首页正文

Node.js readline 逐行读取、写入文件内容的示例

2020-11-27 来源:星星旅游

本文介绍了运用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...'); 
});