Write to a CSV in Node.js
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!'); }});
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.
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.'); });});