1.0.0 • Published 2 years ago

@interaktiv.de/csv-parser v1.0.0

Weekly downloads
-
License
BSD-3-Clause
Repository
github
Last release
2 years ago

Interaktiv CSV Parser

code style: ts-standard Version: 1.0.0

Simple CSV parser for JavaScript/TypeScript.

Table of contents

  1. Installation
  2. API Reference
    1. Functions
      1. fromCsv
        1. Parameters
        2. Options
        3. Return Type
        4. Reference
        5. Examples
      2. toCsv
        1. Parameters
        2. Options
        3. Return Type
        4. Reference
        5. Examples
    2. Types
      1. CsvCellMetadata
        1. Attributes
        2. Reference
      2. CsvParserOptions
        1. Attributes
        2. Reference
      3. CsvParserCallbackFunction
        1. Reference

Installation

# using yarn
$ yarn add @interaktiv.de/csv-parser

# using npm
$ npm i -S @interaktiv.de/csv-parser

API Reference

Functions

fromCsv

The asynchronous fromCsv function parses the input CSV data.

Parameters
NameTypeRequiredDescription
csvstringYesInput CSV data.
optionsCsvParserOptionsNoParsing options.
callbacksRecord<number | string, CsvParserCallbackFunction>NoFunction 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.
Options

The options parameter is of type CsvParserOptions.

NameTypeDefault ValueDescription
headertrue \| string[]trueTrue if first line contains column headers, otherwise an array of strings containing the headers must be provided.
separatorstring','Defines the separator of the CSV data.
stringDelimiter'\'' \| '"''"'Defines the delimiter of strings in the CSV data.
Return Type

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.

Reference

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[]>
Examples
// Sample CSV data
const csv = '1;Alan;Greer;"1971-01-21";ve@kuocu.mu\n'
  + '2;Julian;Chambers;"1971-11-07";oro@het.cy\n'
  + '3;"Anthony Lawrence";Stevens;"2003-05-26";covawe@nehotbeg.rw'

// 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)

toCsv

The asynchronous toCsv function parses an array of objects to CSV.

Parameters
NameTypeRequiredDescription
datastringYesInput CSV data.
optionsOmit<CsvParserOptions, 'header'>NoParsing options.
Options

The options parameter is of type Omit<CsvParserOptions, 'header'>.

NameTypeDefault ValueDescription
separatorstring','Defines the separator of the CSV data.
stringDelimiter'\'' \| '"''"'Defines the delimiter of strings in the CSV data.
Return Type

The function returns a Promise of string.

Reference

The fromCsv function is defined as follows:

async function toCsv (
  data: Array<Record<string | number, any>>,
  {
    separator = ',',
    stringDelimiter = '"'
  }: Omit<CsvParserOptions, 'header'> = {}
): Promise<string>
Examples
// Sample data
const data = [
  {
    id: 1,
    firstname: 'Alan',
    lastname: 'Greer',
    birthdate: new Date(1971-01-21),
    email: 've@kuocu.mu'
  },
  {
    id: 2,
    firstname: 'Julian',
    lastname: 'Chambers',
    birthdate: new Date(1971-11-07),
    email: 'oro@het.cy'
  },
  {
    id: 3,
    firstname: 'Anthony Lawrence',
    lastname: 'Stevens',
    birthdate: new Date(2003-05-26),
    email: 'covawe@nehotbeg.rw'
  }
]

// 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;ve@kuocu.mu
 * 2;Julian;Chambers;1971-11-07T00:00:00.000Z,oro@het.cy
 * 3;Anthony Lawrence;Stevens;2003-05-26T00:00:00.000Z,covawe@nehotbeg.rw
 */

Types

CsvCellMetadata

The interface CsvCellMetadata describes metadata of a cell in CSV data.
It contains information about column and row, as well as parsed cell references.

Attributes
NameTypeDescription
columnIndexnumberColumn count, starting at 1.
columnNamestringColumn name according to CSV column headers.
rowIndexnumberRow count, starting at 1.
cellReferenceA1stringCell reference (position) in MS Excel / LibreOffice Calc A1 notation.
cellReferenceRCstringCell reference (position) in MS Excel / LibreOffice Calc R1C1 notation.
Reference

The interface is defined as follows:

interface CsvCellMetadata {
  readonly columnIndex: number
  readonly columnName: string
  readonly rowIndex: number
  readonly cellReferenceA1: string
  readonly cellReferenceRC: string
}

CsvParserOptions

The interface CsvParserOptions describes the options which may be given to the fromCsv and toCsv function.

Attributes
NameTypeDefault ValueDescription
headertrue \| string[]trueTrue if first line contains column headers, otherwise an array of strings containing the headers must be provided.
separatorstring','Defines the separator of the CSV data.
stringDelimiter'\'' \| '"''"'Defined the delimiter of strings in the CSV data.
Reference

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?: '\'' | '"'
}

CsvParserCallbackFunction

The type CsvParserCallbackFunction describes callback functions for the CSV parser to further parse the string data from CSV.

Reference

The type is defined as follows:

type CsvParserCallbackFunction<T = any> = (str: string, metadata: CsvCellMetadata) => T

Made with by Interaktiv.