Simple CSV parser for JavaScript/TypeScript.
# using yarn
$ yarn add @interaktiv.de/csv-parser
# using npm
$ npm i -S @interaktiv.de/csv-parser
The asynchronous fromCsv function parses the input CSV data.
Name | Type | Required | Description |
---|---|---|---|
csv |
string |
Yes | Input CSV data. |
options |
CsvParserOptions |
No | Parsing options. |
callbacks |
Record<number | string, CsvParserCallbackFunction> |
No | Function callbacks to further parse the strings retrieved from CSV. The keys of the object may be column indices or column headers. The values should be CsvParserCallbackFunctions. |
The options
parameter is of type CsvParserOptions
.
Name | Type | Default Value | Description |
---|---|---|---|
header |
true | string[] |
true |
True if first line contains column headers, otherwise an array of strings containing the headers must be provided. |
separator |
string |
',' |
Defines the separator of the CSV data. |
stringDelimiter |
'\'' | '"' |
'"' |
Defines the delimiter of strings in the CSV data. |
The function returns a Promise of an array of JavaScript objects.
The object keys are the CSV column headers. Each object is a row of CSV.
The type of the Objects may be described using the template R
.
The fromCsv function is defined as follows:
async function fromCsv<R extends Record<string, T>, T = any> (
csv: string,
{ separator = ',', header = true, stringDelimiter = '"' }: CsvParserOptions = {},
callbacks: Record<number | string, CsvParserCallbackFunction<T>> = {}
): Promise<R[]>
// Sample CSV data
const csv = '1;Alan;Greer;"1971-01-21";[email protected]\n'
+ '2;Julian;Chambers;"1971-11-07";[email protected]\n'
+ '3;"Anthony Lawrence";Stevens;"2003-05-26";[email protected]'
// Interface describing return type
interface User {
readonly id: number
readonly firstname: string
readonly lastname: string
readonly birthdate: Date
readonly email: string
}
// Calling fromCsv
const userData: User[] = await fromCsv<User>(
csv,
{
separator: ';',
header: ['id', 'firstname', 'lastname', 'birthdate', 'email'],
},
{
id: str => parseInt(str),
birthdate: str => new Date(str)
}
)
console.log(userData.map(({ id }) => id)) // [1, 2, 3]
console.log(userData[1].birthdate) // Date(1971-11-07T23:00:00.000Z)
The asynchronous toCsv function parses an array of objects to CSV.
Name | Type | Required | Description |
---|---|---|---|
data |
string |
Yes | Input CSV data. |
options |
Omit<CsvParserOptions, 'header'> |
No | Parsing options. |
The options
parameter is of type Omit<CsvParserOptions, 'header'>
.
Name | Type | Default Value | Description |
---|---|---|---|
separator |
string |
',' |
Defines the separator of the CSV data. |
stringDelimiter |
'\'' | '"' |
'"' |
Defines the delimiter of strings in the CSV data. |
The function returns a Promise of string.
The fromCsv function is defined as follows:
async function toCsv (
data: Array<Record<string | number, any>>,
{
separator = ',',
stringDelimiter = '"'
}: Omit<CsvParserOptions, 'header'> = {}
): Promise<string>
// Sample data
const data = [
{
id: 1,
firstname: 'Alan',
lastname: 'Greer',
birthdate: new Date(1971-01-21),
email: '[email protected]'
},
{
id: 2,
firstname: 'Julian',
lastname: 'Chambers',
birthdate: new Date(1971-11-07),
email: '[email protected]'
},
{
id: 3,
firstname: 'Anthony Lawrence',
lastname: 'Stevens',
birthdate: new Date(2003-05-26),
email: '[email protected]'
}
]
// Calling toCsv
const csv = await toCsv(
data,
{ separator: ';' }
)
console.log(csv)
/*
* id;firstname;lastname;birthdate;email
* 1;Alan;Greer;1971-01-21T00:00:00.000Z;[email protected]
* 2;Julian;Chambers;1971-11-07T00:00:00.000Z,[email protected]
* 3;Anthony Lawrence;Stevens;2003-05-26T00:00:00.000Z,[email protected]
*/
The interface CsvCellMetadata
describes metadata of a cell in CSV data.
It contains information about column and row, as well as parsed cell references.
Name | Type | Description |
---|---|---|
columnIndex |
number |
Column count, starting at 1. |
columnName |
string |
Column name according to CSV column headers. |
rowIndex |
number |
Row count, starting at 1. |
cellReferenceA1 |
string |
Cell reference (position) in MS Excel / LibreOffice Calc A1 notation. |
cellReferenceRC |
string |
Cell reference (position) in MS Excel / LibreOffice Calc R1C1 notation. |
The interface is defined as follows:
interface CsvCellMetadata {
readonly columnIndex: number
readonly columnName: string
readonly rowIndex: number
readonly cellReferenceA1: string
readonly cellReferenceRC: string
}
The interface CsvParserOptions
describes the options which may be given to the fromCsv
and toCsv
function.
Name | Type | Default Value | Description |
---|---|---|---|
header |
true | string[] |
true |
True if first line contains column headers, otherwise an array of strings containing the headers must be provided. |
separator |
string |
',' |
Defines the separator of the CSV data. |
stringDelimiter |
'\'' | '"' |
'"' |
Defined the delimiter of strings in the CSV data. |
The interface is defined as follows:
interface CsvParserOptions {
/**
* True if first line contains column headers, otherwise an array of strings containing the headers may be given
* @default true
*/
header?: true | string[]
/**
* Defines the separator to use
* @default ','
*/
separator?: ',' | ';' | '\t'
/**
* Defines the delimiter of strings
* @default '"'
*/
stringDelimiter?: '\'' | '"'
}
The type CsvParserCallbackFunction
describes callback functions for the CSV parser to further parse the string data from CSV.
The type is defined as follows:
type CsvParserCallbackFunction<T = any> = (str: string, metadata: CsvCellMetadata) => T
Made with ❤️ by Interaktiv.