基本的にファイルを応答にストリーミングする基本的な node.js アプリ コードを作成して、ストリーミングをテストしています。hereおよびhereのコードを使用します。
しかし、からリクエストを行い、http://127.0.0.1:8000/
別のブラウザを開いて別のファイルをリクエストすると、最初のファイルが完了するまで 2 番目のファイルのダウンロードが開始されません。私の例では、1GB のファイルを作成しました。dd if=/dev/zero of=file.dat bs=1G count=1
しかし、最初のファイルのダウンロード中にさらに 3 つのファイルを要求すると、最初のファイルのダウンロードが完了すると、3 つのファイルが同時にダウンロードを開始します。
現在のダウンロードが完了するのを待つ必要がなく、各リクエストに応答するようにコードを変更するにはどうすればよいですか?
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/');