将多个文件传送到一个响应 [英] Pipe multiple files to one response

查看:102
本文介绍了将多个文件传送到一个响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为响应编写两个文件和一些其他文本. 但是,下面的代码仅返回第一个文件,仅此而已!"文字.

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

推荐答案

您需要的是双工流,它将数据从一个流传递到另一个流.

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

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

在上面的示例中,第一个管道将所有数据从stream写入到duplexStream,然后将数据从duplexStream写入到stream2,最后stream2将您的数据写入到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.

这是write方法的一种可能实现的示例.

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

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

这篇关于将多个文件传送到一个响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆