除了使用Response.write()
方法来分块发送和Response.end()
标记结束!
如果你有一个流!您可以将其直接通过管道传递给Response对象!一切都会自动处理!
有关文件可读流,请参见下面的示例:
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
// The filename is simple the local directory and tacks on the requested url
var filename = __dirname+req.url;
// This line opens the file as a readable stream
var readStream = fs.createReadStream(filename);
// This will wait until we know the readable stream is actually valid before piping
readStream.on('open', function () {
// This just pipes the read stream to the response object (which goes to the client)
readStream.pipe(res); // <====== here
});
// This catches any errors that happen while creating the readable stream (usually invalid names)
readStream.on('error', function(err) {
res.end(err);
});
}).listen(8080);
您可以使用任何 Stream 做到这一点。只需将其通过管道传递给 Respond 对象!
上面的例子来自这里:
https://nodejs.org/en/knowledge/advanced/streams/how-to-use-fs-create-read-stream/
底线
使用管道!它也很好看和更好地理解!
这是来自文档的链接!
https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
readable.pipe() 方法将Writable流附加到readable,使其自动切换到流动模式并将其所有数据推送到附加的 Writable。
并注意链接
可以将多个 Writable 流附加到单个 Readable 流。
readable.pipe() 方法返回对目标流的引用,从而可以设置管道流链
例子:
const fs = require('fs');
const r = fs.createReadStream('file.txt'); // read stream
const z = zlib.createGzip(); // write stream
const w = fs.createWriteStream('file.txt.gz'); // write stream
r.pipe(z).pipe(w);
阅读文档以获取更多信息!