Q:

Node.js: how to pass a readStream as function argument and use in a callback?

I want to pass a stream as argument to a function and use it in an async callback but it is destroyed (stream.readable is false)
for example:
var test = require('./test');
var file = fs.createReadStream('./file.txt');
test(file, console.log);

and in test.js:
module.exports = function(stream, callback) {
    //stream.pipe(process.stdout); ///////// STREAM IS READABLE HERE 
    doSomething('abc', function(err) {
         stream.pipe(process.stdout); ///////// STREAM IS NOT READABLE HERE
         callback(err);
    });
};
enter code here

why is this happening ?
what can I do to use it in the callback ?

A:

This happens because stream ends before you trying to pipe it. In the first place stream is readable because you synchronous code still working. In the second place (inside of callback) stream already ended because callback may be executed after several ticks in future. You need to pasue your streem if you want to read it in future. This code should work:
var test = require('./test');
var file = fs.createReadStream('./file.txt');
file.pause();
test(file, console.log);

test.js
module.exports = function(stream, callback) {
    doSomething('abc', function(err) {
         stream.resume();
         stream.pipe(process.stdout);
         callback(err);
    });
};

