如何使用json2csv创build后下载CSV文件

我正在使用json2csv节点模块生成一个CSV文件,其中的数据写得非常好。 这是我的代码与我的数据创build一个CSV文件。

  Lead.find({ownerId:owner._id}, function(err, data){ if(err){res.json(err)} else{ res.json(data); var fields = ['lead', 'salutation', 'fname','lname','title','email','mobile','rating','address','city','state','zcode','company','industry','empSize','lsource']; var csv = json2csv({ data: data, fields: fields }); var path='./public/csv/file'+Date.now()+'.csv'; fs.writeFile(path, csv, function(err,data) { if (err) {throw err;} else{ console.log('file Created'); //I need to download above creating csv file here } }); } }); 

所以,现在我想知道如何在生成csv后下载创build的CSV文件。 我试过res.setHeader('Content-disposition', 'attachment; filename=data.csv'); res.set('Content-Type', 'text/csv'); res.status(200).send(data); res.setHeader('Content-disposition', 'attachment; filename=data.csv'); res.set('Content-Type', 'text/csv'); res.status(200).send(data);

但它不工作…

请让我知道我该怎么做。

谢谢

如果您使用Express 4.x,则可以简单地使用res.download()

  Lead.find({ownerId:owner._id}, function(err, data){ if(err){res.json(err)} else{ var fields = ['lead', 'salutation', 'fname','lname','title','email','mobile','rating','address','city','state','zcode','company','industry','empSize','lsource']; var csv = json2csv({ data: data, fields: fields }); var path='./public/csv/file'+Date.now()+'.csv'; fs.writeFile(path, csv, function(err,data) { if (err) {throw err;} else{ res.download(path); // This is what you need } }); } }); 
 json2csv({ data: myCars, fields: fields }, function(err, csv) { if(err) { throw err; } else { var path='./csv'+Date.now()+'.csv'; fs.writeFile(path, csv, function(err,data) { if (err) {throw err;} else{ console.log('file Created'); res.setHeader('Content-disposition', 'attachment; filename=data.csv'); res.set('Content-Type', 'text/csv'); res.status(200).send(csv); //I need to download above creating csv file here } }); } }); 

用这个replace你的代码。

在尝试所有这些…..我得到了一个解决scheme。 在Node.js的API后台res.download(path)工作正常。 在前面我使用Angular.js。 所以,为了使它可行,我需要创build一个锚点标签,并触发像这样的点击事件

var anchor=angular.element('<a/>'); anchor.attr({href:'data:attachment/csv;charset=utf-8,' + encodeURI($scope.dattaa),target:'_blank',download:'lead'+Date.now()+'.csv'})[0].click();

现在它工作正常。

谢谢你们的帮助。