I am new to NodeJS. I am trying to download file from json object. I have json object that i received from Mongodb collection and I want to return json data as list in file. I tried to download file from my local machine and that codes works. But not able to understand how should i return file from json object. Do i need to use Buffer for this. So far I have below test code.
//Write Member File
exports.File = function(req, res){
var data = getdata(function(err, members){
//console.log(members);
// var bf = buffer.Buffer(members, 'Binary').toString('base64');
// console.log(bf.length);
// I get bf.length as 4
var file = 'C:/Docs/members.txt';
var filename = path.basename(file);
console.log(filename);
var mimetype = 'text/plain';
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);
var fileStream = fs.createReadStream(file);
fileStream.pipe(res);
});
};
This works with me.
var user = {"name":"azraq","country":"egypt"};
var json = JSON.stringify(user);
var filename = 'user.json';
var mimetype = 'application/json';
res.setHeader('Content-Type', mimetype);
res.setHeader('Content-disposition','attachment; filename='+filename);
res.send( json );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With