Ask Your Question
1

How can I save data to a CSV file using Node.js?

asked 2023-06-04 18:40:04 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-04 18:46:02 +0000

qstack gravatar image

You can use the built-in fs module in Node.js to write data to a CSV file. Here's an example:

const fs = require('fs');

const data = [
  ['Name', 'Age', 'Country'],
  ['John', 30, 'USA'],
  ['Jane', 25, 'Canada'],
  ['Bob', 40, 'UK'],
];

const csvContent = data.map(row => row.join(',')).join('\n');

fs.writeFile('data.csv', csvContent, (err) => {
  if (err) throw err;
  console.log('Data saved to data.csv');
});

In this example, we're creating an array of arrays that represents the CSV data we want to write. Each inner array represents a row in the CSV file. We're then using the map function to convert each row to a comma-separated string, and then joining all the rows together into a single string with newline characters separating each row.

Finally, we use the writeFile function from the fs module to write the CSV content to a file named data.csv. The callback function is called once the write operation completes, and logs a message to the console.

You can modify this example to use your own data, and customize the file path and name as needed.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-04 18:40:04 +0000

Seen: 15 times

Last updated: Jun 04 '23