首页 > 解决方案 > fs.createWriteStream 下载到项目的根文件夹(不需要)

问题描述

我正在从我的 MongoDB fs.files 集合中下载一个文件。为此,我需要将 Gridfs Bucket 的 downloadStream 传输到 fs 的 createWriteFileStream。在 createWriteStream 的“完成”时,我只想将文件发送到客户端响应,而不是让 fs 将文件放在项目的文件夹中。

router.get("/download", function(req, res) {
  setTimeout(download, 1000);
  function download() {
      var bucket = new mongodb.GridFSBucket(localDatabase())
      bucket.openDownloadStreamByName(file)
        .pipe(fs.createWriteStream(file))
          .on('error', function(error) {
            assert.ifError(error)
          })
          .on('finish', function() {
            console.log(`Downloaded ${file}`)
            res.download(file)
            return
          })
  }
});

标签: node.js

解决方案


Perhaps you can pipe directly from openDownloadStreamByName() to res and avoid the intermediate temporary file. You will probably need to set appropriate headers to simulate the res.download() behavior.

Otherwise, to control the location of the temporary file, you will need to create a full path to that temporary location and use that full path with fs.createWriteStream(). Then, you'll probably want to remove the temporary file after it's been sent.


推荐阅读