Marcus Johansson
Marcus Johansson

Reputation: 2667

Pipe multiple files to one response

I'm trying to write two files and some more text to a response. The code below does however only return the first file and the "Thats all!" text.

var http = require('http'),
    util = require('util'),
    fs   = require('fs');

server = http.createServer(function(req, res){  
    var stream  = fs.createReadStream('one.html'),
        stream2 = fs.createReadStream('two.html');

    stream.on('end', function(){
        stream2.pipe(res, { end:false});
    });

    stream2.on('end', function(){
        res.end("Thats all!");
    });

    res.writeHead(200, {'Content-Type' : 'text/plain'});
    stream.pipe(res, { end:false});

}).listen(8001);

Upvotes: 3

Views: 4179

Answers (2)

Doron Segal
Doron Segal

Reputation: 2260

you can use stream-stream It's a pretty basic node module (using no dependencies)

var ss = require('stream-stream');
var fs = require('fs');

var files = ['one.html', 'two.html'];
var stream = ss();

files.forEach(function(f) {
    stream.write(fs.createReadStream(f));
});
stream.end();

res.writeHead(200, {'Content-Type' : 'text/plain'});
stream.pipe(res, { end:false});

Upvotes: 0

mechanicious
mechanicious

Reputation: 1616

What you need is a Duplex stream, which will pass the data from one stream to another.

stream.pipe(duplexStream).pipe(stream2).pipe(res);

In the example above the first pipe will write all data from stream to duplexStream then there will be data written from the duplexStream to the stream2 and finally stream2 will write your data to the res writable stream.

This is an example of one possible implementation of the write method.

DuplexStream.write = function(chunk, encoding, done) {
   this.push(chunk);
}

Upvotes: 1

Related Questions