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');
Can someone help?
Thanks!
Run the Node.js Download CSV File AppRun the Node. js App with command: node src/server. js . Now you can use browser or a HTTP Client to send GET request to http://localhost:8080/api/csv/download .
Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited).
Click on the given Export to HTML table to CSV File button to download the data to CSV file format. The file will download by the name of person. csv. You can open this file in MS-Excel to see the data contained inside it.
var path = require('path'); var mime = require('mime'); var fs = require('fs'); app. get('/download', function(req, res){ var file = __dirname + '/upload-folder/dramaticpenguin. MOV'; var filename = path. basename(file); var mimetype = mime.
Use res.send if you use express.
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With