【发布时间】:2021-04-05 18:00:05
【问题描述】:
在node js和express中学习了两种下载文件的方式,但是没搞清楚它们有什么区别:res.download(path)和createReadStream(path)。
我知道createReadStream() 正在创建一个流以了解服务器溢出,这是一个好方法,但是另一个呢?
这是两个例子:
const orderId = req.params.orderId;
const invoiceName = 'invoice-' + orderId + '.pdf';
const invoicePath = path.join('data', 'invoices', invoiceName)
res.download(invoicePath, (err) => {
if (err) {
return next(err);
}
});
和
const readStream = fs.createReadStream(invoicePath);
res.setHeader('Content-type', 'application/pdf');
res.setHeader('Content-Dispoition', 'attachment; filename=' + invoiceName);
readStream
.on('open', function () {
// This just pipes the read stream to the response object (which goes to the client)
readStream.pipe(res);
})
.on('end', function () {
readStream.unpipe(res);
console.log('All the data in the file has been read');
})
.on('close', function (err) {
console.log('Stream has been Closed');
next(err)
});
【问题讨论】: