@push.rocks/smartcsv

Small, typed CSV handling for TypeScript projects. @push.rocks/smartcsv turns CSV strings into object arrays, turns object arrays back into CSV strings, and keeps the API intentionally compact for browser and Node.js usage.

Issue Reporting and Security

For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.

Install

Use pnpm to add the package:

pnpm add @push.rocks/smartcsv

What It Does

@push.rocks/smartcsv focuses on the common CSV workflows you usually need inside application code:

  • parse CSV text into typed JavaScript objects
  • use the first CSV row as object keys
  • auto-detect comma , or semicolon ; separators
  • handle quoted cells that contain separators
  • optionally remove UTF-8 BOM markers
  • optionally trim whitespace around headers and values
  • serialize arrays of objects into CSV strings

Quick Start

import { Csv } from '@push.rocks/smartcsv';

const csvText = `name;role;city
"Ada Lovelace";"Mathematician";"London"
"Grace Hopper";"Computer scientist";"New York"`;

const csv = await Csv.createCsvFromString(csvText, {
  headers: true,
  unquote: true,
  trimSpace: true,
  removeBomMarkers: true,
});

const rows = await csv.exportAsObject();

console.log(rows);
// [
//   { name: 'Ada Lovelace', role: 'Mathematician', city: 'London' },
//   { name: 'Grace Hopper', role: 'Computer scientist', city: 'New York' }
// ]

Parsing CSV Strings

Create a Csv instance with Csv.createCsvFromString(csvString, options). The method prepares the parser and returns a reusable Csv instance.

import { Csv } from '@push.rocks/smartcsv';

const csv = await Csv.createCsvFromString(
  'Product,Price,Available\nNotebook,12.5,true\nPen,1.2,true',
  {
    headers: true,
    unquote: true,
    trimSpace: true,
    removeBomMarkers: true,
  }
);

const products = await csv.exportAsObject();

Result:

[
  { Product: 'Notebook', Price: '12.5', Available: 'true' },
  { Product: 'Pen', Price: '1.2', Available: 'true' },
];

Parsed values are returned as strings because CSV is a text format. Convert numbers, booleans, or dates in your application layer after parsing.

Parser Options

export interface ICsvConstructorOptions {
  headers: boolean;
  unquote?: boolean;
  trimSpace?: boolean;
  removeBomMarkers?: boolean;
}
Option Default Description
headers required When true, the first row is used as object keys.
unquote true Removes quotes from quoted headers and values. Quoted cells can contain separators.
trimSpace true Trims leading and trailing whitespace from headers and values.
removeBomMarkers true Removes a UTF-8 BOM marker from the beginning of the input string.

Separator Detection

The parser counts commas and semicolons in the input and uses the more common separator. If both appear equally often, comma is used.

const semicolonCsv = await Csv.createCsvFromString('a;b\n1;2', {
  headers: true,
});

console.log(semicolonCsv.keyFrame); // ';'

Quoted Cells

With unquote: true, quoted values are protected before splitting rows. This allows separators inside quoted cells:

const csv = await Csv.createCsvFromString('name,note\n"Ada","uses commas, safely"', {
  headers: true,
  unquote: true,
});

const rows = await csv.exportAsObject();

console.log(rows[0].note); // 'uses commas, safely'

Creating CSV Strings

Use Csv.createCsvStringFromArray() to serialize an array of objects. The method builds the header row from all keys found across all objects, preserving first-seen key order.

import { Csv } from '@push.rocks/smartcsv';

const csvText = await Csv.createCsvStringFromArray([
  { name: 'Ada', role: 'Mathematician' },
  { name: 'Grace', city: 'New York' },
]);

console.log(csvText);

Output:

name,role,city
Ada,Mathematician,
Grace,,New York

Missing values are serialized as empty cells. Values are converted with String(value ?? '').

API

Csv.createCsvFromString(csvString, options)

Creates and initializes a Csv instance from a CSV string.

const csv = await Csv.createCsvFromString(csvString, { headers: true });

csv.exportAsObject()

Serializes the parsed CSV data into an array of objects and stores it on csv.data.

const rows = await csv.exportAsObject();

Csv.createCsvStringFromArray(array)

Creates a CSV string from an array of flat objects.

const csvText = await Csv.createCsvStringFromArray([
  { id: 1, name: 'Ada' },
  { id: 2, name: 'Grace' },
]);

Public Instance Properties

Property Type Description
csvString string The normalized CSV string used internally by the parser.
headers string[] Parsed header names.
keyFrame ',' | ';' Detected separator.
data Record<string, string>[] Last exported object rows.
options ICsvConstructorOptions Effective parser options.

TypeScript Types

export type TCsvCellValue = string | number | boolean | null | undefined;
export type TCsvObjectRow = Record<string, TCsvCellValue>;
export type TCsvParsedRow = Record<string, string>;

TCsvObjectRow is used when creating CSV strings from objects. TCsvParsedRow is used when parsing CSV text back into objects.

Runtime Support

@push.rocks/smartcsv is an ESM package and ships TypeScript declarations. It is tested for Node.js and Chromium-based browser environments through @git.zone/tstest.

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the LICENSE file.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

Company Information

Task Venture Capital GmbH Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

S
Description
A module for handling CSV data compliant with Gitzone standard.
Readme 606 KiB
Languages
TypeScript 100%