假设我有一个包含整数列表的文件,每行一个。我使用fs.createReadStream
并将其管道传输到split
(因此每个块都是一个整数)。然后我将其管道传输到一个双工流中,该流应该将数字相加并通过管道写入fs.createWriteStream
来写入总和。
var fs = require('fs');
var stream = require('stream');
var split = require('split');
var addIntegers = new stream.Duplex();
addIntegers.sum = 0;
addIntegers._read = function(size) {
this.push(this.sum + 'n');
}
addIntegers._write = function(chunk, encoding, done) {
this.sum += +chunk;
done();
}
fs.createReadStream('list-of-integers.txt')
.pipe(split())
.pipe(addIntegers)
.pipe(fs.createWriteStream('sum.txt'));
当我运行它时,sum.txt
只是不断地用零填充,程序永远不会终止(如预期的那样)。在允许输出流(fs.createWriteStream
)从addIntegers
读取之前,如何等待输入流(split
)为空?
我想通了。
我决定改用转换流(感谢 mscdex),因为它有一个方法(_flush
),在消耗所有写入数据后被调用。工作代码如下。不要忘记npm i split
:)
var fs = require('fs');
var stream = require('stream');
var split = require('split');
var addIntegers = new stream.Transform();
addIntegers.sum = 0;
addIntegers._transform = function(chunk, encoding, done) {
this.sum += +chunk;
done();
}
addIntegers._flush = function(done) {
this.push(this.sum + 'n');
}
fs.createReadStream('list-of-integers.txt')
.pipe(split())
.pipe(addIntegers)
.pipe(fs.createWriteStream('sum.txt'));