我想从MongoDB GridFs中读取文件,并将其附加到从节点邮件程序发送的邮件中。因此,我需要在服务器端读取此文件,这意味着我无权访问http请求或响应对象,并且无法通过管道将读取的流传递给Internet上多个位置建议的响应。
我读取文件并作为缓冲区发送的代码如下-
let _fetchFileById = async (fileId, options) => {
let db = options.db
, gfs = Grid(db, mongo)
, filename = fileId
, file_buf = new Buffer('buffer');
return new Promise((resolve,reject) => {
gfs.collection('jobdescription')
let readstream = gfs.createReadStream({
filename: filename
, root: 'jobdescription'
})
readstream.on('data', function (chunk) {
console.log("writing!!!");
// file_buf.push(chunk)
if (!file_buf)
file_buf = chunk;
else file_buf = Buffer.concat([file_buf, chunk]);
});
readstream.on('end', function () {
// var buffer = Buffer.concat(file_buf);
db.close();
console.log(`returning`)
// console.log(file_buf)
resolve(file_buf)
})
})
}
当我将file_buf用作节点邮件程序中附件的输入时,我得到了以下错误-
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type object
。任何帮助或指针将不胜感激。
答案 0 :(得分:1)
最后,我没有找到一种方法来读取文件并直接从方法中返回它,但是我做了一个小的解决方法,即从db中读取文件并将其临时存储在本地目录中,一旦我将其附加到nodemailer上,我打算将其删除。我在这里发布方法,以防万一它有用-
exports.downloadFile = async (req, fileName) => {
let db = req.headers.options.db
, gridfs = Grid(db, mongo)
gridfs.collection('jobdescription')
if (gridfs) {
let fsstreamwrite = fs.createWriteStream(
path.join(process.cwd(), `./app/jobdescriptions/${fileName}`)
)
let readstream = gridfs.createReadStream({
filename: fileName
})
readstream.pipe(fsstreamwrite);
return readstream.on("close", file => {
console.log("File Read successfully from database");
return file;
})
} else {
console.log("Sorry No Grid FS Object");
}
}