任何嚴格的JavaScript處理將阻止。 response.write()
,至少爲V0.8的,是no exception這樣:
The first time response.write()
is called, it will send the buffered header information and the first body to the client. The second time response.write()
is called, Node assumes you're going to be streaming data, and sends that separately. That is, the response is buffered up to the first chunk of body.
Returns true
if the entire data was flushed successfully to the kernel buffer. Returns false
if all or part of the data was queued in user memory. 'drain'
will be emitted when the buffer is again free.
什麼可以節省一些時間試圖write()
它之前longString
轉換爲Buffer
,因爲轉換會發生反正:
var longString = 'a';
for (...) { ... }
longString = new Buffer(longString);
但是,它可能會更好stream的longString
各塊,而不是全在一次(注:Streams are changing in v0.10):
var longString = 'a',
chunkCount = Math.pow(2, 29),
bufferSize = Buffer.byteLength(longString),
longBuffer = new Buffer(longString);
function download(request, response) {
var current = 0;
response.setHeader("Content-Length", bufferSize * chunkCount);
response.setHeader("Content-Type", "application/force-download");
response.setHeader("Content-Disposition", 'attachment; filename="file"');
function writeChunk() {
if (current < chunkCount) {
current++;
if (response.write(longBuffer)) {
process.nextTick(writeChunk);
} else {
response.once('drain', writeChunk);
}
} else {
response.end();
}
}
writeChunk();
}
而且,如果最終目標是從流磁盤上的文件,這可能是更容易與fs.createReadStream()
和stream.pipe()
:
function download(request, response) {
// response.setHeader(...)
// ...
fs.createReadStream('./file-on-disk').pipe(response);
}
不會創建該字符串只有一次,在服務器啓動時? – Vanuan 2013-02-11 19:02:08
是的,但是對每個請求都構建了響應。所以它被複製爲每個響應。響應是I/O密集型,同時也考慮到其龐大的規模。 – user568109 2013-02-11 19:12:16
對我而言,1 MB在不到一秒鐘內加載完畢,您是如何設法點擊這麼快的? – Vanuan 2013-02-11 19:30:33