Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download csv file node.js

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!

like image 960
Trung Tran Avatar asked Feb 01 '16 19:02

Trung Tran


People also ask

How do I download a CSV file from node JS?

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 .

How do I download a CSV file?

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).

How do I download a CSV file in Javascript?

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.

How do I download a file from node js server?

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.


1 Answers

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);
  });
});
like image 62
Kiechlus Avatar answered Oct 15 '22 12:10

Kiechlus