Sravan
Sravan

Reputation: 18647

Node js download csv file and notify response in browser

Hello currently I m working on a MEAN-Stack applicaiton Node and Angular1

My task is to export JSON to csv and to download it.

I am using Json2csv Plugin.

Here is the code I applied,

exports.exportCsv = function(req, res, next) {
  var users = req.body.users;
  if (users.length > 0) {
    var fields = ['_id', 'firstName', 'email'];
    try {
      var result = json2csv({ data: users, fields: fields });
      var path = Date.now() + '.csv';
      fs.writeFile(path, result, function(err, resu) {
        if (err) {
          return ext.returnError(res, err, 500);
        } else {
          res.download(path);
        }
      });
    } catch (err) {
      console.error(err);
    }
  } else {
    console.error('error');
  }
};

This code works fine and the file is getting downloaded but,

I can't see in browser that it is getting downloaded. How to I send the response to browser so that it gets downloaded as all other files get.

How do the user get noticed that the file got downloaded. The file is getting download without showing in downloads.

Upvotes: 0

Views: 751

Answers (2)

Abhilasha
Abhilasha

Reputation: 1225

Try this

res.download(path);
res.status(201).send('downloaded');

And then check the error code or response message in API call on frontend.

Upvotes: 1

user8556290
user8556290

Reputation:

try this, i am no sure what you got as res but to be sure, look on it.

 else {
      res.download(path);
      res.msg = "ok ...";
      alert(res);//object res
      //wich attributes property got res (show us)
      for(var i in res){
         console.log(i);//attr
         console.log(res[i]);//value
      }
      alert(res.msg);//res from us inside js
    }

Upvotes: 0

Related Questions