Generating CSV file with Fast-csv in Nodejs

Asked

Viewed 123 times

1

I need to write a CSV with data from a JSON, but I cannot generate the file with the data. I am using fast-csv Package. No error is reported during execution.

Follows my code:

   async function generateCsv() {

   const fastcsv = require("fast-csv");
   const fs = require("fs");
   var path = "../csv/final_dataset.csv";
   const ws = fs.createWriteStream(path, { flags: "w" });

   db.query("SELECT * FROM distance", (error, result) => {

   const jsonData = JSON.parse(JSON.stringify(result.rows));
   console.log(jsonData);

   fastcsv
  .write(jsonData, { headers: true, duplicates: false })
  .on("finish", function () {
    console.log("Write to csv successfully!");
  })
  .pipe(ws);
  });
  }

  module.exports = {
    generateCsv,
  };

Data I intend to write to CSV. Console result.log(jsonData):

[
 { id: 1420, date: '2021-03-26', distance: '3.7889199999999996' },
 { id: 1421, date: '2021-03-25', distance: '3.6386399999999997' },
 { id: 1422, date: '2021-03-31', distance: '0.5502699999999999' },
 { id: 1423, date: '2021-04-01', distance: '0.97' },
 { id: 1424, date: '2021-03-29', distance: '0.5358499999999999' },
 { id: 1425, date: '2021-03-28', distance: '0.59277' },
 { id: 1432, date: '2021-04-04', distance: '0.58139' }
]

When running this example function, the CSV file is not generated with the content in the specified path. Someone can help?

  • Hello Matheus. It’s important [Edit] and add a [mcve] of the problem, with a step by step of what you have already done and explain clearly and objectively what you need. Do not delete and do not repeat the question, just edit and wait for the reopening process. To take better advantage of the site, understand and avoid closures is worth reading the Stack Overflow Survival Guide in English. Thank you for understanding.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.