我正在测试流,通过创建一个基本的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