@dilanluna/csv-parser
v1.0.1
Published
Parse csv files into javascript objects
Maintainers
Readme
CSV Parser
Simple and lightweight package to parse csv files into javascript objects.
Installation
Package require node.js version 10 or above, and can be installed with npm:
$ npm install @dilanluna/csv-parserUsage
Import the module in your app.
import csvParser from '@dilanluna/csv-parser';Or if you're using commonjs:
const csvParser = require('@dilanluna/csv-parser').default;The csvParser is a function that accepts the following configuration object:
{
filePath: string;
separator?: string;
extractHeaderFromFirstLine?: boolean;
}Configuration in detail.
| Property | Description | Default |
| ---------------------------- | ------------------------------------------------------------------- | ------- |
| filePath | Path to csv file. This property is required. | |
| separator | Separator character of the csv file. | ";" |
| extractHeaderFromFirstLine | Determines if headers are extracted from the first line of the file | false |
Once called to csvParser function with apropiate config, it returns a Promise resolved with an array of parsed objects or rejected if something went wrong.
Example
Supose you have a csv file called fruits.csv like this:
banana;12
apple;5
melon;4
watermelon;2In your code you parse this file something like this:
import csvParser from '@dilanluna/csv-parser';
const fruits = await csvParser({
filePath: 'fruits.csv',
});
console.log(fruits);
// Output
// [
// { 0: 'banana', 1: '12' },
// { 0: 'apple', 1: '5' },
// { 0: 'melon', 1: '4' },
// { 0: 'watermelon', 1: '2' }
// ]You can map keys in the parsed object from the first line of the csv file.
Adding headers in the first line
name;count
banana;12
apple;5
melon;4
watermelon;2Now add extractHeaderFromFirstLine to configuration object.
import csvParser from '@dilanluna/csv-parser';
const fruits = await csvParser({
filePath: 'fruits.csv',
extractHeaderFromFirstLine: true,
});
console.log(fruits);
// Output
// [
// { name: 'banana', count: '12' },
// { name: 'apple', count: '5' },
// { name: 'melon', count: '4' },
// { name: 'watermelon', count: '2' }
// ]