2013-07-02 37 views
1

假設我有一個功能​​。該API是這樣的(其中|,事實上,管道):創建一個流通過數據通過子流程與streams2

inputStream | BlackBox | outputStream 

然而,​​實際上是一個require('child_process').spawn的包裝,所以實際上它看起來是這樣的:

inputStream | BlackBox.Writable -> proc.stdin -> proc.stdout -> BlackBox.Readable | outputStream 

我可以用streams1輕鬆做到這一點,但我想了解streams2以及它如何更好。因此,我到目前爲止的代碼如下:

var Duplex = require('stream').Duplex 
var spawn = require('child_process').spawn 
var util = require('util') 

util.inherits(BlackBox, Duplex) 

function BlackBox() { 
    Duplex.call(this) 

    // Example process 
    this.proc = spawn('convert', ['-', ':-']) 

    var that = this 
    this.proc.stdout.on('end', function() { 
    that.push(null) 
    }) 
} 

BlackBox.prototype._write = function (chunk, encoding, callback) { 
    return this.proc.stdin.write(chunk, encoding, callback) 
} 

BlackBox.prototype.end = function (chunk, encoding, callback) { 
    return this.proc.stdin.end(chunk, encoding, callback) 
} 

BlackBox.prototype._read = function (size) { 
    var that = this 

    this.proc.stdout.on('readable', function() { 
    var chunk = this.read(size) 
    if (chunk === null) 
     that.push('') 
    else 
     that.push(chunk) 
    }) 
} 

我在這裏做了什麼不對嗎?

我最關心的是從文檔以下摘錄於readable._read(size)

數據可用時,將其放入讀隊列調用readable.push(塊)。如果push返回false,那麼你應該停止閱讀。當再次調用_read時,您應該開始推送更多數據。

我該如何「停止閱讀」?

爲了清楚起見,我想要回壓和節流來處理。

回答