node.js - 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
})
}
});
解决方案
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.
推荐阅读
- go - How to index entire GOPATH for existing project in Goland?
- javascript - amCharts 不显示 json 数据
- http - Indy 10 HTTPS 代理
- sql - PIVOT 多列不考虑聚合结果
- command-line - 由于权限更改导致的总线错误(核心转储)
- c# - 使用 { get; 将 .json 反序列化为 C# 放; } (牛顿软件)
- angular - 从 Angular 2 迁移到 Angular 4 后,模块“AppModule”导入错误意外值“t”。请添加@NgModule 注释
- mysql - 可以使用普通的 MySql jdbc 驱动程序写入 Mariadb。那为什么要使用单独的 MaraDB 驱动程序呢?
- c# - transform.forward 仅适用于 0,0,0 旋转,我想让它独立于旋转
- ansible - Ansible - 将字符串与变量组合以形成现有变量