Pipe multiple files to one response

故事扮演 提交于 2019-12-24 02:57:39

问题


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);

回答1:


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);
}



回答2:


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});


来源:https://stackoverflow.com/questions/10462649/pipe-multiple-files-to-one-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!