CSV Writer
Convert objects/arrays into a CSV string or write them into a file.
Prerequisite
Usage
The example below shows how you can write records defined as the array of objects into a file.
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const csvWriter = createCsvWriter({
path: 'path/to/file.csv',
header: [
{id: 'name', title: 'NAME'},
{id: 'lang', title: 'LANGUAGE'},
]
});
const records = [
{name: 'Bob', lang: 'French, English'},
{name: 'Mary', lang: 'English'}
];
csvWriter.writeRecords(records)
.then(() => {
console.log('...Done');
});
You can keep writing records into the same file by calling writeRecords
multiple times (but need to wait for the fulfillment
of the promise
of the previous writeRecords
call)
Promise.resolve()
.then(() => csvWriter.writeRecords(records1))
.then(() => csvWriter.writeRecords(records2))
...
If you don't want to write a header line, don't give title
to header elements and just give field ids as a string.
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const csvWriter = createCsvWriter({
path: 'path/to/file.csv',
header: ['name', 'lang']
});
If each record is defined as an array, use createArrayCsvWriter
to get an csvWriter
.
const createCsvWriter = require('csv-writer').createArrayCsvWriter;
const csvWriter = createCsvWriter({
header: ['NAME', 'LANGUAGE'],
path: 'path/to/file.csv'
});
var records = [
['Bob', 'French, English'],
['Mary', 'English']
];
csvWriter.writeRecords(records)
.then(() => {
console.log('...Done');
});
If you just want to get a CSV string but don't want to write into a file,
you can use createObjectCsvStringifier
(or createArrayCsvStringifier
)
to get an csvStringifier
.
const createCsvStringifier = require('csv-writer').createObjectCsvStringifier;
const csvStringifier = createCsvStringifier({
header: [
{id: 'name', title: 'NAME'},
{id: 'lang', title: 'LANGUAGE'},
]
});
const records = [
{name: 'Bob', lang: 'French, English'},
{name: 'Mary', lang: 'English'}
];
console.log(csvStringifier.getHeaderString());
console.log(csvStringifier.stringifyRecords(records));
API
createObjectCsvWriter(params)
Parameters:
- params
<Object>
-
path <string>
Path to a write file
-
header <Array<{id, title}|string>>
Array of objects (id
and title
properties) or strings (field ids)
-
encoding <string>
(optional)
Returns:
createArrayCsvWriter(params)
Parameters:
Returns:
CsvWriter#writeRecords(records)
Parameters:
-
records <Array<Object|Array>>
Depending on which function was used to create a csvWriter
(i.e. createObjectCsvWriter
or createArrayCsvWriter
),
records will be either an array of objects or arrays
Returns:
createObjectCsvStringifier(params)
Parameters:
Returns:
Returns:
ObjectCsvStringifier#stringifyRecords(records)
Parameters:
Returns:
createArrayCsvStringifier(params)
Parameters:
Returns:
Returns:
ArrayCsvStringifier#stringifyRecords(records)
Parameters:
- records
<Array<Array<string>>>
Returns: