1

假设我有一个函数BlackBox。api是这样的(|实际上,管道在哪里):

inputStream | BlackBox | outputStream

但是,BlackBox实际上是 a 的包装器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(chunk) 将其放入读取队列。如果 push 返回 false,那么您应该停止阅读。当再次调用 _read 时,您应该开始推送更多数据。

我如何“停止阅读”?

需要明确的是,我希望处理背压和节流。

4

1 回答 1

1

isaacs 基本上做了一个例子:https ://github.com/isaacs/duplex-passthrough

于 2013-07-16T05:22:43.687 回答