2016-03-22 39 views
0

假設我有一個包含整數列表的文件,每行一個。我使用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)爲空?

+1

爲什麼'push()'在_write()裏面呢? – mscdex

+0

嗯是的,我可以在'_write'中使用變換流和this.push(this.sum +'\ n')'。我以這種方式得到了一個總得分比永遠好得多的總分。但是,有什麼辦法可以獲得總體總數? (一次寫入'sum.txt'而不是n次?)。後來我意識到我可以「尾隨-n 1 sum.txt」,但我想知道是否有一種慣用的'節點'方式來獲得我想要的。 – aeoliant

回答

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')); 
相關問題