write to a csv file in javascript

To write to a CSV file in Javascript, we can make use of the built-in Node.js fs module. Here's an example code snippet:

index.tsx
const fs = require('fs');

// the data we want to write
const csvData = 'first_name,last_name,email\nJohn,Doe,john@example.com\nJane,Doe,jane@example.com';

// write to file
fs.writeFile('myData.csv', csvData, (err) => {
  if (err) throw err;
  console.log('Data written to file');
});
286 chars
11 lines

In this example, we first require the fs module. Then we define the CSV data we want to write as a string. Finally, we use the fs.writeFile() method to write the data to a file called myData.csv.

The writeFile() method takes three arguments: the file path/name to write the data to, the data to write, and a callback function to execute when the writing is complete.

The callback function receives an err argument in case an error occurred during the writing process. If no error occurred, the function simply logs a message to the console.

gistlibby LogSnag