6

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);
    });
};

3 Answers 3

5

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 );
Sign up to request clarification or add additional context in comments.

Comments

5

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();
    }
});

Comments

0

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);
    });
};

3 Comments

I tried your solution but it return empty file and takes so long to download file. I can see data in console.log(members). But it doesn't come in file.
What does console.log(json) put?
console.log(members) put json array data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.