res.download()和createReadStream()下载文件的区别

The difference between res.download() and createReadStream() in downloading files

学习了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)
    });

简要查看 express res.download() 源代码,它基本上自动化了您使用替代示例手动执行的操作。这包括依靠流进行高效传输和最小化内存占用。

https://github.com/expressjs/express/blob/master/lib/response.js

它实际上最终调用了第 1016 行定义的 sendfile() 函数——最终调用了 file.pipe(res).