suppose I have a function BlackBox. the api is something like this (where | are, in fact, pipes):
inputStream | BlackBox | outputStream
However, BlackBox is actually a wrapper for a require('child_process').spawn, so really it looks like this:
inputStream | BlackBox.Writable -> proc.stdin -> proc.stdout -> BlackBox.Readable | outputStream
I can easily do this with streams1, but I want to understand streams2 and how it is better. Thus, I have the following code so far:
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)
})
}
Am I doing anything wrong here?
My main concern is the following excerpt from the documentation on readable._read(size):
When data is available, put it into the read queue by calling readable.push(chunk). If push returns false, then you should stop reading. When _read is called again, you should start pushing more data.
how do i "stop reading"?
To be clear, I want back pressure and throttling to be handled.
isaacs basically made an example: https://github.com/isaacs/duplex-passthrough