As streams are becoming more and more popular in node.js I’m trying to get a deep understanding of them. I looked at the code of popular modules like JSONStream and event-stream and read through the stream-handbook.
There is still one thing that I don’t understand. I sometimes see the following pattern:
main.js:
var module = require('./module')
module('something').pipe(process.stdout)
module.js:
var Stream = require('stream')
module.exports = function(string) {
var stream = new Stream()
stream.readable = true
stream.resume = function() {
stream.emit('data', string)
stream.emit('end')
}
process.nextTick(stream.resume)
return stream
}
I think this is really confusing because I would look for the pipe function inside the module.js. In the example I have to look for this one line process.nextTick() and then find the function that is called. As a beginner you might not know what process.nextTick() does and therefore have no chance to understand what the module does.
Is this pattern some sort of “best practice” for writing streaming modules? Why not implement the logic inside a stream.pipe = function(dest){}?
Not totally clear on the issue you’re raising, but the use of
process.nextTick()in these cases is to allow the user of the module to add its'data', etc. event handlers after the stream is created but before any events are emitted. In your examplestream.pipeisn’t required, it’s just being used as the stream’s event handler in the client; that’s why it isn’t inmodule.js.