@coolgk/csv
a javascript / typescript module
npm install @coolgk/csv
read and write csv files
Report bugs here: https://github.com/coolgk/node-utils/issues
Examples
import { Csv } from '@coolgk/csv';
const csv = new Csv({
tmpConfig: { dir: '/tmp/csv' }
});
const arrayData = [
[1,2,3,4,5],
[6,7,7,8,9],
[0,5,8,90,65]
];
const objectData = [
{col1: 'ab', col2: 'cd', col3: 'ef'},
{col1: '2ab', col2: '2cd', col3: '2ef'},
{col1: '3ab', col2: '3cd', col3: '3ef'}
];
csv.createFile(
arrayData,
{
columns: ['column 1', 'column 2', 'column 3', 'h4', 'h5'],
formatter: (row) => {
return row.map((value) => 'formatted-' + value);
}
}
).then((csvFilePath) => {
console.log(csvFilePath);
read(csvFilePath, ['column 1', 'column 2', 'column 3', 'h4', 'h5']);
});
csv.createFile(
objectData,
{
columns: ['col1', 'col2', 'col3'],
formatter: (row) => {
return [row.col1 + '+format', row.col2 + '+format', row.col3 + '+format'];
}
}
).then((csvFilePath) => {
console.log(csvFilePath);
read(csvFilePath, ['col1', 'col2', 'col3']);
});
function read (file, columns) {
const lines = csv.readFile(file, {columns: columns});
lines.forEach(
(lineArray, index) => {
console.log(lineArray, index);
},
(total) => {
console.log('read done, total:', total);
}
);
const lines2 = csv.readFile(file);
lines2.forEach(
(lineArray, index) => {
console.log(lineArray, index);
},
(total) => {
console.log('read done, total:', total);
}
);
}