我正在測試流,通過創建一個基本的node.js應用程序代碼,基本上流文件到響應。使用來自here和here的代碼。響應每個請求,而不必等到當前流完成
但是,如果我從http://127.0.0.1:8000/
發出請求,然後打開另一個瀏覽器並請求另一個文件,第二個文件將不會開始下載,直到第一個文件完成。在我的例子中,我創建了一個1GB的文件。 dd if=/dev/zero of=file.dat bs=1G count=1
但是,如果我要求三個文件而第一個被下載,這三個文件將開始,一旦第一個文件已完成同時下載。
我該如何更改代碼,以便它在每個請求發出響應時不必等待當前下載完成?
var http = require('http');
var fs = require('fs');
var i = 1;
http.createServer(function(req, res) {
console.log('starting #' + i++);
// This line opens the file as a readable stream
var readStream = fs.createReadStream('file.dat', { bufferSize: 64 * 1024 });
// This will wait until we know the readable stream is actually valid before piping
readStream.on('open', function() {
console.log('open');
// This just pipes the read stream to the response object (which goes to the client)
readStream.pipe(res);
});
// This catches any errors that happen while creating the readable stream (usually invalid names)
readStream.on('error', function(err) {
res.end(err);
});
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
您使用的是哪個版本的節點?流從版本v0.10更改。 http://blog.nodejs.org/2012/12/20/streams2/ – Andrew
不是這個問題了,因爲我已經接受你的答案,但記錄:'v0.10.4' – capdragon