Write to a CSV in Node.js

Solution 1:

You can use fs (https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback):

var dataToWrite;
var fs = require('fs');

fs.writeFile('form-tracking/formList.csv', dataToWrite, 'utf8', function (err) {
  if (err) {
    console.log('Some error occured - file either not saved or corrupted file saved.');
  } else{
    console.log('It\'s saved!');
  }
});

Solution 2:

The docs for node-csv-parser (npm install csv) specifically state that it can be used with streams (see fromStream, toStream). So it's not hard-coded to use stdout.

Several other CSV parsers also come up when you npm search csv -- you might want to look at them too.

Solution 3:

Here is a simple example using csv-stringify to write a dataset that fits in memory to a csv file using fs.writeFile.

import stringify from 'csv-stringify';
import fs from 'fs';

let data = [];
let columns = {
  id: 'id',
  name: 'Name'
};

for (var i = 0; i < 10; i++) {
  data.push([i, 'Name ' + i]);
}

stringify(data, { header: true, columns: columns }, (err, output) => {
  if (err) throw err;
  fs.writeFile('my.csv', output, (err) => {
    if (err) throw err;
    console.log('my.csv saved.');
  });
});

Solution 4:

If you want to use a loop as you say you can do something like this with Node fs:

let fs = require("fs")

let writeStream = fs.createWriteStream('/path/filename.csv')

someArrayOfObjects.forEach((someObject, index) => {     
    let newLine = []
    newLine.push(someObject.stringPropertyOne)
    newLine.push(someObject.stringPropertyTwo)
    ....

    writeStream.write(newLine.join(',')+ '\n', () => {
        // a line was written to stream
    })
})

writeStream.end()

writeStream.on('finish', () => {
    console.log('finish write stream, moving along')
}).on('error', (err) => {
    console.log(err)
})

Solution 5:

In case you don't wanna use any library besides fs, you can do it manually.

let fileString = ""
let separator = ","
let fileType = "csv"
let file = `fileExample.${fileType}`

Object.keys(jsonObject[0]).forEach(value=>fileString += `${value}${separator}`)
    fileString = fileString.slice(0, -1)
    fileString += "\n"

    jsonObject.forEach(transaction=>{
        Object.values(transaction).forEach(value=>fileString += `${value}${separator}`)
        fileString = fileString.slice(0, -1)
        fileString += "\n"
    })

fs.writeFileSync(file, fileString, 'utf8')