运用readline逐行读取,在写入行数数据时用两种思路实现。

效果图如下:
左边1.log 为源文件
右边1.readline.log为复制后的文件
下边为命令行输出

readline.preview

实现方式一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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...');
});

实现方式二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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...');
});

About Sodino