2012-05-05 9 views
2

2つのファイルといくつかのテキストを応答に書き込もうとしています。 ただし、以下のコードは、最初のファイルと "Thats all!"テキスト。複数のファイルを1つの応答にパイプする

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

必要なのは、デュプレックスストリームです。デュプレックスストリームは、あるストリームから別のストリームへデータを渡します。最初のパイプ上の例では

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

、その後stream2、最後にstream2duplexStreamから書き込まれたデータはres書き込み可能なストリームにデータを書き込みますが存在しますstreamからduplexStreamにすべてのデータを書き込みます。

これは、writeメソッドの1つの実装例です。

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

あなたはそれが(依存関係を使用していない)

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}); 
かなり基本的なノードモジュールです ストリームストリームを使用することができます
関連する問題