append to a csv file in javascript

To append data to a CSV file using Node.js, you can use the fs module. First, you need to open the file using the appendFile() method which takes three arguments: the file name, the data to append, and an optional callback. If the file doesn't exist, it will be created.

Here's an example code snippet:

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

const data = 'John,Doe,31\n';

fs.appendFile('people.csv', data, (err) => {
  if (err) throw err;
  console.log('Data appended to file');
});
169 chars
9 lines

In this example, we are appending a single row of data to a file named people.csv. The data consists of three comma-separated values representing the first name, last name, and age of a person.

If you want to append multiple rows, you can concatenate them into a single string and pass it as the second argument of the appendFile() method.

Note that when working with CSV files, you should handle the possibility of values containing commas or newlines by properly escaping them or enclosing them in quotes.

gistlibby LogSnag