Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file from Json object in Node.js

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);
    });
};
like image 224
Gayatri Avatar asked Aug 21 '14 19:08

Gayatri


1 Answers

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 );
like image 188
Ahmed Azraq Avatar answered Oct 17 '22 20:10

Ahmed Azraq