假设我有一个包含整数列表的文件,每行一个。我使用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
只是不断填充零,程序永远不会终止(如预期的那样)。在允许输出流(split
)从fs.createWriteStream
读取之前,如何等待输入流(addIntegers
)为空?
答案 0 :(得分:0)
我明白了。
我决定使用Transform流代替(感谢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'));