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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bernierllc/csv-parser

v0.3.0

Published

Atomic CSV parsing utilities with encoding support

Readme

@bernierllc/csv-parser

Atomic CSV parsing utilities with robust quote and encoding handling.

Features

  • Pure CSV Parsing: Focused on parsing CSV content without validation or business logic
  • Robust Quote Handling: Properly handles quoted fields, escaped quotes, and unclosed quotes
  • Flexible Formatting: Convert data back to CSV format with customizable options
  • Type Safety: Full TypeScript support with strict typing
  • Zero Dependencies: No external dependencies, pure Node.js/TypeScript
  • Comprehensive Testing: 90%+ test coverage with extensive edge case testing

Installation

npm install @bernierllc/csv-parser

Quick Start

import { parseCSV, formatCSV } from '@bernierllc/csv-parser';

// Parse CSV content
const csv = `name,age,city
"John Doe",30,"New York"
"Jane Smith",25,"Los Angeles"`;

const result = parseCSV(csv);
console.log(result.headers); // ['name', 'age', 'city']
console.log(result.rows); // [['John Doe', '30', 'New York'], ['Jane Smith', '25', 'Los Angeles']]

// Format data back to CSV
const data = [
  ['name', 'age', 'city'],
  ['John Doe', 30, 'New York'],
  ['Jane Smith', 25, 'Los Angeles']
];

const formatted = formatCSV(data);
console.log(formatted);
// name,age,city
// John Doe,30,New York
// Jane Smith,25,Los Angeles

API Reference

Parsing Functions

parseCSV(csvContent, options?)

Parse CSV content into headers and rows.

function parseCSV(
  csvContent: string, 
  options?: CSVParserOptions
): CSVParsedResult

Parameters:

  • csvContent: The CSV content as a string
  • options: Optional parsing configuration

Returns:

  • headers: Array of column headers
  • rows: 2D array of data rows
  • totalRows: Total number of rows (including header)
  • dataRows: Number of data rows (excluding header)

Example:

const csv = `name,age,city
John Doe,30,New York
Jane Smith,25,Los Angeles`;

const result = parseCSV(csv);
// result.headers = ['name', 'age', 'city']
// result.rows = [['John Doe', '30', 'New York'], ['Jane Smith', '25', 'Los Angeles']]

parseCSVLine(line, options?)

Parse a single CSV line.

function parseCSVLine(
  line: string, 
  options?: CSVParserOptions
): CSVLineResult

Returns:

  • fields: Array of parsed fields
  • isQuoted: Whether the line has unclosed quotes
  • originalLength: Original line length

Example:

const line = '"John Doe",30,"New York"';
const result = parseCSVLine(line);
// result.fields = ['John Doe', '30', 'New York']
// result.isQuoted = false

validateCSV(csvContent, options?)

Validate CSV content for common issues.

function validateCSV(
  csvContent: string, 
  options?: CSVParserOptions
): CSVValidationResult

Returns:

  • isValid: Whether the CSV is valid
  • error: Error message if invalid
  • errorLine: Line number where error occurred
  • errorColumn: Column number where error occurred
  • errorType: Type of error

Example:

const csv = `name,age,city
John Doe,30,New York`;

const result = validateCSV(csv);
// result.isValid = true

getColumnCount(line, options?)

Get the number of columns in a CSV line.

function getColumnCount(
  line: string, 
  options?: CSVParserOptions
): number

Example:

const count = getColumnCount('John Doe,30,New York'); // 3

isLineQuoted(line, options?)

Check if a CSV line is properly quoted.

function isLineQuoted(
  line: string, 
  options?: CSVParserOptions
): boolean

Example:

const quoted = isLineQuoted('"John Doe,30,"New York"'); // true

Formatting Functions

formatCSVValue(value, options?)

Format a single value for CSV output.

function formatCSVValue(
  value: any, 
  options?: CSVFormatOptions
): string

Example:

formatCSVValue('John, Doe'); // '"John, Doe"'
formatCSVValue('He said "Hello"'); // '"He said ""Hello"""'

formatCSVRow(values, options?)

Format an array of values as a CSV row.

function formatCSVRow(
  values: any[], 
  options?: CSVFormatOptions
): string

Example:

const row = formatCSVRow(['John Doe', 30, 'New York']);
// 'John Doe,30,New York'

formatCSV(data, options?)

Format a 2D array of data as CSV content.

function formatCSV(
  data: any[][], 
  options?: CSVFormatOptions
): string

Example:

const data = [
  ['name', 'age', 'city'],
  ['John Doe', 30, 'New York'],
  ['Jane Smith', 25, 'Los Angeles']
];

const csv = formatCSV(data);
// name,age,city
// John Doe,30,New York
// Jane Smith,25,Los Angeles

formatCSVWithHeaders(headers, rows, options?)

Format data with headers as CSV content.

function formatCSVWithHeaders(
  headers: string[], 
  rows: any[][], 
  options?: CSVFormatOptions
): string

Example:

const headers = ['name', 'age', 'city'];
const rows = [
  ['John Doe', 30, 'New York'],
  ['Jane Smith', 25, 'Los Angeles']
];

const csv = formatCSVWithHeaders(headers, rows);
// name,age,city
// John Doe,30,New York
// Jane Smith,25,Los Angeles

formatCSVFromObjects(objects, options?)

Format an array of objects as CSV content.

function formatCSVFromObjects(
  objects: Record<string, any>[], 
  options?: CSVFormatOptions
): string

Example:

const objects = [
  { name: 'John Doe', age: 30, city: 'New York' },
  { name: 'Jane Smith', age: 25, city: 'Los Angeles' }
];

const csv = formatCSVFromObjects(objects);
// name,age,city
// John Doe,30,New York
// Jane Smith,25,Los Angeles

createCSVTemplate(headers, sampleRows?, options?)

Create a CSV template with headers and optional sample data.

function createCSVTemplate(
  headers: string[], 
  sampleRows?: any[][], 
  options?: CSVFormatOptions
): string

Example:

const headers = ['name', 'age', 'city'];
const sampleRows = [
  ['John Doe', 30, 'New York'],
  ['Jane Smith', 25, 'Los Angeles']
];

const template = createCSVTemplate(headers, sampleRows);
// name,age,city
// John Doe,30,New York
// Jane Smith,25,Los Angeles

escapeCSVString(str, quoteChar?)

Escape a string for CSV output.

function escapeCSVString(
  str: string, 
  quoteChar?: string
): string

Example:

escapeCSVString('Hello "World"'); // 'Hello ""World""'

unescapeCSVString(str, quoteChar?)

Unescape a CSV string.

function unescapeCSVString(
  str: string, 
  quoteChar?: string
): string

Example:

unescapeCSVString('Hello ""World""'); // 'Hello "World"'

Configuration Options

CSVParserOptions

interface CSVParserOptions {
  /** Character used to separate fields (default: ',') */
  delimiter?: string;
  /** Whether to trim whitespace from values (default: true) */
  trim?: boolean;
  /** Whether to skip empty rows (default: true) */
  skipEmptyRows?: boolean;
  /** Whether to preserve quotes in output (default: false) */
  preserveQuotes?: boolean;
  /** Character encoding of the input (default: 'utf-8') */
  encoding?: string;
}

CSVFormatOptions

interface CSVFormatOptions {
  /** Character used to separate fields (default: ',') */
  delimiter?: string;
  /** Whether to quote all fields (default: false) */
  quoteAll?: boolean;
  /** Whether to quote fields containing delimiter (default: true) */
  quoteDelimiter?: boolean;
  /** Whether to quote fields containing quotes (default: true) */
  quoteQuotes?: boolean;
  /** Whether to quote fields containing newlines (default: true) */
  quoteNewlines?: boolean;
  /** Quote character to use (default: '"') */
  quoteChar?: string;
  /** Line ending to use (default: '\n') */
  lineEnding?: string;
}

Advanced Examples

Custom Delimiters

import { parseCSV, formatCSV } from '@bernierllc/csv-parser';

// Parse semicolon-separated values
const ssv = `name;age;city
John Doe;30;New York
Jane Smith;25;Los Angeles`;

const result = parseCSV(ssv, { delimiter: ';' });

// Format with custom delimiter
const formatted = formatCSV(result.rows, { delimiter: ';' });

Handling Complex Data

import { parseCSV, formatCSVFromObjects } from '@bernierllc/csv-parser';

// Parse complex CSV with quoted fields
const csv = `name,description,address
"John ""The Rock"" Doe","Software Engineer, Senior","123 Main St, Apt 4B, New York, NY"
"Jane Smith","Product Manager","456 Oak Ave, Los Angeles, CA"`;

const result = parseCSV(csv);

// Convert to objects and back
const objects = result.rows.map(row => ({
  name: row[0],
  description: row[1],
  address: row[2]
}));

const formatted = formatCSVFromObjects(objects);

Validation and Error Handling

import { parseCSV, validateCSV } from '@bernierllc/csv-parser';

const csv = `name,age,city
John Doe,30,New York
Jane Smith,25,Los Angeles,extra`;

// Validate before parsing
const validation = validateCSV(csv);
if (!validation.isValid) {
  console.error(`CSV Error: ${validation.error}`);
  console.error(`Line: ${validation.errorLine}, Column: ${validation.errorColumn}`);
  return;
}

// Safe to parse
const result = parseCSV(csv);

Template Generation

import { createCSVTemplate } from '@bernierllc/csv-parser';

// Create a template for user data import
const headers = ['first_name', 'last_name', 'email', 'phone', 'department'];
const sampleRows = [
  ['John', 'Doe', '[email protected]', '(555) 123-4567', 'Engineering'],
  ['Jane', 'Smith', '[email protected]', '(555) 987-6543', 'Marketing']
];

const template = createCSVTemplate(headers, sampleRows);
console.log(template);
// first_name,last_name,email,phone,department
// John,Doe,[email protected],(555) 123-4567,Engineering
// Jane,Smith,[email protected],(555) 987-6543,Marketing

Error Handling

The parser provides detailed error information for common CSV issues:

  • Empty files: CSV content is empty
  • Unclosed quotes: Unclosed quote in line X
  • Missing data: CSV must have at least a header row and one data row
  • Mismatched columns: Row X has Y columns, expected Z

Performance

The parser is optimized for performance with:

  • Minimal memory allocation
  • Efficient string processing
  • No external dependencies
  • Streaming-friendly design

Testing

Run the test suite:

npm test
npm run test:coverage

Contributing

This package follows the Bernier LLC coding standards:

  • TypeScript strict mode
  • Comprehensive test coverage
  • Clear documentation
  • Atomic, focused functionality

License

Copyright (c) 2025 Bernier LLC

This file is licensed to the client under a limited-use license. The client may use and modify this code only within the scope of the project it was delivered for. Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.