Outputs data to a CSV file using NodeJS.
Install the fast-csv
NodeJS package:
npm i fast-csv
Create a new .js
file with the following sample code:
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const csv = require('fast-csv');
/**
* Writes data stored in an object literal to a CSV file path
**/
const createCsv = (data, filename) => {
const csvFile = path.resolve(__dirname, filename);
const csvStream = csv.format({ headers: true });
csvStream.write(data);
csvStream.pipe(fs.createWriteStream(csvFile, { encoding: 'utf8' } ))
csvStream.end();
return `Finished writing data to: ${csvFile}`;
}
const data = {
'Col 1': 'Foo',
'Col 2': 'Bar',
'Col 3': 42,
}
const result = createCsv(data, 'test.csv');
console.log(result);
Another example that passes an an nested array of row arrays with set headers:
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const csv = require('fast-csv');
/**
* Writes data stored in an object literal to a CSV file path
**/
const createCsv = (data, filename) => {
const csvFile = path.resolve(__dirname, filename);
// pass the array of headers to format() method
const csvStream = csv.format({ headers: data.headers });
// loop over nested row arrays
const arr = data.rows;
for (let i = 0; i<arr.length; i++) {
let row = arr[i];
csvStream.write( row );
}
csvStream.end();
csvStream.pipe(fs.createWriteStream(csvFile, { encoding: 'utf8' } ))
return `Finished writing data to: ${csvFile}`;
}
const data = {
headers: ['Col 1', 'Col 2'],
rows: [
['Foo', 'Bar'],
['Hello', 'World'],
['Life', 42],
['Test 1', 'Test 2']
]
};
const result = createCsv(data, 'test.csv');
console.log(result);
In a terminal run the code with: node path/to/nodejs/script.js