title: Download csv file node.js
body: <p>I am building an app using node.js and trying to download data as a csv file. I am using json2csv (<a href="https://www.npmjs.com/package/json2csv" rel="noreferrer">https://www.npmjs.com/package/json2csv</a>) 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 <code>/downloads</code> folder. Here is my current code:</p>
  
  <pre><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'); 
  </code></pre>
  
  <p>Can someone help?</p>
  
  <p>Thanks!</p>