Node js下载csv文件并在浏览器中通知响应

时间:2017-09-09 14:01:39

标签: angularjs json node.js csv

您好我目前正在处理MEAN-Stack申请NodeAngular1

我的任务是将JSON导出到csv并下载。

我正在使用Json2csv插件。

以下是我申请的代码,

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

此代码工作正常,文件正在下载,但

我无法在浏览器中看到它已下载。 如何将响应发送到浏览器,以便在所有其他文件获得时下载。

用户如何注意到文件已下载。该文件正在下载而不显示在下载中。

2 个答案:

答案 0 :(得分:1)

试试这个

▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯ 42%

然后检查前端API调用中的错误代码或响应消息。

答案 1 :(得分:0)

尝试这个,我不确定你得到什么作为res但是要确定,看看它。

 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
    }