Reputation: 559
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);
});
};
Upvotes: 6
Views: 10186
Reputation: 792
You can try this.
function(req, res) {
var jsonObj = getJSON();
var data = JSON.stringify(jsonObj);
res.setHeader('Content-disposition', 'attachment; filename= myFile.json');
res.setHeader('Content-type', 'application/json');
res.write(data, function (err) {
res.end();
}
});
Upvotes: 5
Reputation: 587
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 );
Upvotes: 5
Reputation: 665456
Do i need to use Buffer for this.
No, a simple string that you .write()
to the response will suffice.
exports.returnData = function(req, res){
getdata(function(err, members){
console.log(members); // I guess you have an object here, not a plain response
var json = JSON.stringify(members); // so let's encode it
var filename = 'result.json'; // or whatever
var mimetype = 'application/json';
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);
res.write(json);
});
};
Upvotes: 0