I want to read file from MongoDB GridFs and attach it to mail sent from node mailer. So I need to read this file at server side, what this means is I do not have access to http request or response object and I can not pipe the read stream to response suggested in multiple places over the internet.
My code to read the file and send as buffer is as below -
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)
})
})
}
when I am using the file_buf as input to the attachment in node mailer i am getting below errror -
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type object
. Any help or pointers would be really appreciated.