下载csv文件node.js [英] Download csv file node.js
本文介绍了下载csv文件node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用node.js构建应用程序,并尝试将数据下载为csv文件.我为此使用json2csv( https://www.npmjs.com/package/json2csv )目的.但是,按照我的配置方式,.csv文件存储在应用程序的根目录中.我希望将文件下载下载给用户-例如,文件应出现在用户的/downloads
文件夹中.这是我当前的代码:
I am building an app using node.js and trying to download data as a csv file. I am using json2csv (https://www.npmjs.com/package/json2csv) for this purpose. However, the way I have it configured, the .csv file gets stored in my app's root directory. I want the file to be sent to the user as a download - for example, the file should appear in the user's /downloads
folder. Here is my current code:
var fields = ['car', 'price', 'color'];
var myCars = [
{
"car": "Audi",
"price": 1,
"color": "blue"
}, {
"car": "BMW",
"price": 1,
"color": "black"
}, {
"car": "Porsche",
"price": 1,
"color": "green"
}
];
json2csv({ data: myCars, fields: fields }, function(err, csv) {
if (err) console.log(err);
fs.writeFile('file.csv', csv, function(err) { //currently saves file to app's root directory
if (err) throw err;
console.log('file saved');
});
});
var file = '../software-project-metric-dashboard/file.csv';
res.download(file, 'testfile.csv');
有人可以帮忙吗?
谢谢!
推荐答案
如果使用您必须定义一个类似于以下内容的HTTP GET路由:
You have to define a HTTP GET route which looks something like that:
app.get("/pathToYourDownload", function (req, res) {
json2csv({ data: myCars, fields: fields }, function(err, csv) {
res.setHeader('Content-disposition', 'attachment; filename=data.csv');
res.set('Content-Type', 'text/csv');
res.status(200).send(csv);
});
});
这篇关于下载csv文件node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文