npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@interaktiv.de/csv-parser

v1.0.0

Published

Simple CSV parser for JavaScript.

Downloads

3

Readme

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

| 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. |

Options

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. |

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";[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)

toCsv

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

Parameters

| Name | Type | Required | Description | |-------------|--------------------------------------------------------------------------|----------|------------------| | data | string | Yes | Input CSV data. | | options | Omit<CsvParserOptions, 'header'> | No | Parsing options. |

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. |

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: '[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]
 */

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

| 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. |

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

| 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. |

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.