任何严格的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