【问题标题】:The difference between res.download() and createReadStream() in downloading filesres.download() 和 createReadStream() 下载文件的区别
【发布时间】: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)
    });

【问题讨论】:

    标签: node.js express download


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 2016-03-07
      • 2019-05-25
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 2020-04-12
      相关资源
      最近更新 更多