18

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!

Trung Tran
  • 13,141
  • 42
  • 113
  • 200
  • Are you or do you plan to use a framework like express or do you just want to have a server for this use only? – cviejo Feb 01 '16 at 19:39
  • I am using the express framework @cviejo – Trung Tran Feb 01 '16 at 19:41
  • Try following this, get back if you encounter any issues: http://stackoverflow.com/questions/7288814/download-a-file-from-nodejs-server-using-express – cviejo Feb 01 '16 at 19:43
  • don't use fs.writeFile, instead just send the content with the proper content type, the same way you'd send html content to the client. – Kevin B Feb 01 '16 at 19:52

3 Answers3

34

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);
  });
});
Kiechlus
  • 1,167
  • 12
  • 21
18

On express server:

const json2csv = require('json2csv').parse;

const csvString = json2csv(yourDataAsArrayOfObjects);
res.setHeader('Content-disposition', 'attachment; filename=shifts-report.csv');
res.set('Content-Type', 'text/csv');
res.status(200).send(csvString);

On client (otherwise most of the browsers will not download the file, even you will see the proper response in the network panel):

window.open(downloadUrl);
Alexander
  • 7,484
  • 4
  • 51
  • 65
  • 3
    Upvoted this answer because even though I had reached the point where all the data was actually there, the browser would not download it as a file. The "window.open" was the missing part on the client's side! – georgbc Jun 18 '20 at 17:40
  • 1
    Thanks for the tip: I did find that on both Mac/PC it seemed to work fine. Just using a normal pug file with an "a". 2020. – Fattie Oct 21 '20 at 16:09
1

You can easliy achieve with a npm package

On express server:

    const csvwriter = require('csv-writer');
    let createCsvWriter = csvwriter.createObjectCsvWriter;
    router.get('/downloadcsvfromJSON', (req, res) => {
         const dataArray= [{"id":"1","name":"BOB"},{"id":"2","name":"JACK"}];
         const path = 'sample.csv';
         const csvWriter = createCsvWriter({
           path: path,
           header: [{ id:'id',title:'ID'},{id:'name',title:'Name' }]});
         });
         try 
         {
              csvWriter.writeRecords(userLogsArray)
              .then(() => {res.download(path);});
         }
         catch (error) 
         {
           console.log(error);
         }

On browser:

http://localhost:3000/downloadcsvfromJSON/

You will be able to download the csv file.