Reputation: 5659
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.
Upvotes: 4
Views: 1826
Reputation: 5659
Finally i did not find a way to read file and return it directly from method, however I did a small workaround by reading it from db and storing it in local directory temporarily, once i attach it to nodemailer I intend to delete it. I am posting the method here, just in case it helps some one -
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");
}
}
Upvotes: 2