This provides a set of parser classes for CSV to and from JSON.
If the debug
library is available (npm i debug
) you can see debug information with DEBUG='CSV*'
environment variable.
This will read a CSV file and return JSON objects from it. It will use the first row in the CSV file to create the properties in the result object.
(async () => {
const reader = new CSVReader('input.csv', {/* options */);
await reader.open();
while (!reader.isOver) {
const entry = await reader.readNext();
// It is possible in certain cases that the last return entry is null
if (!entry) break;
console.log(entry.myNamedColumn);
}
await reader.close();
})();
chunkSize
: Amount of bytes to read in each chunk. Defaults to1 * 1024 * 1024
(1mb).separator
: Column separator in CSV file. Defaults to comma (,
).rowSeparator
: Row separator in CSV file. Defaults to line break (\n
).
This will write a CSV file from the JSON objects passed to it. It will use the properties in the first JSON object as the columns for the CSV file. Any property not existing in the first passed object will not be added to the CSV file!
(async () => {
const writter = new CSVWritter('output.csv', {/* options */);
await writter.open();
for (let i = 0; i < 100000; i++) {
await writter.write({
id: i,
otherColumn: 'test',
});
}
await writter.close();
})();
separator
: Column separator in CSV file. Defaults to comma (,
).rowSeparator
: Row separator in CSV file. Defaults to line break (\n
).