CSV Utils
A TypeScript library for CSV manipulation, featuring robust error handling, strong typing, and a fluent interface. This library provides comprehensive utilities for parsing, transforming, analyzing, and writing CSV data / arrays of objects, with support for operations like header mapping, streaming for large files, schema validation, and async processing.
Table of Contents
Features
- ๐ Type Safety - Comprehensive TypeScript support with generic types for robust data handling.
- ๐งฉ Flexible Header Mapping - Sophisticated transformation between flat CSV columns and nested object structures, including mapping to/from array properties.
- ๐ Rich Data Operations - Extensive methods for querying, filtering, updating, sorting, grouping, and aggregating data.
- ๐ Advanced Transformations - Powerful tools for data conversion, including
join, pivot, unpivot, addColumn, castColumnType, and more.
- โก Async & Parallel Processing - Efficiently handle large files with asynchronous operations, stream processing, and worker thread support for CPU-intensive tasks.
- ๐ก๏ธ Robust Error Handling - Custom
CSVError class and configurable retry mechanisms for I/O operations.
- ๐ Extensive Preamble Support - Read, store, and write CSV preambles (additional header lines/comments).
- ๐ Fluent Interface (Builder Pattern) - Chain methods for elegant and readable data manipulation pipelines.
- ๐ง Smart Custom Type Casting - Define custom logic to test and parse string values into specific types (numbers, dates, booleans, custom objects) on a global or per-column basis.
- ๐ High-Performance Streaming API -
CSVStreamProcessor for processing massive CSV files with minimal memory footprint, featuring a fluent API.
- ๐ Schema Validation - Integrated support for data validation against
StandardSchemaV1 (compatible with Zod and other validation libraries), with modes for erroring, filtering, or keeping invalid data.
- โ๏ธ Memory Efficiency - Stream processing uses Node.js backpressure to manage memory usage for large datasets.
- ๐ฆ Batch Processing - Optimized methods for processing data in configurable batches for improved throughput in async operations.
- ๐ฆ Standalone Functions - Alternative functional programming style for all core operations.
Installation
npm install @doeixd/csv-utils
# or
yarn add @doeixd/csv-utils
# or
pnpm add @doeixd/csv-utils
The published package supports Node.js 16 and later. For development and release checks, use Node.js 24 LTS (24.11 or later).
Quick Start
For more check out the dedicated quick start guide
import CSV, { CSVUtils } from '@doeixd/csv-utils';
interface Product {
id: string;
name: string;
price: number;
category: string;
inventory?: number;
currency?: string;
}
// Read from a CSV file (assuming price is numeric in CSV or cast later)
const products = CSV.fromFile<Product>('products.csv');
// Chain operations
const result = products
.findRowsWhere(p => p.price > 100) // Find expensive products
.update({ currency: 'USD' }) // Add currency field
.updateColumn('price', p => p * 0.9) // Apply 10% discount
.sortBy('price', 'desc') // Sort by price (high to low)
.removeWhere(p => (p.inventory ?? 0) < 5) // Remove low inventory items
.toArray(); // Get the results as an array
// Write back to file
CSVUtils.writeCSV('discounted_products.csv', result);
// Alternatively, write using the CSV instance
// CSV.fromData(result).writeToFile('discounted_products.csv');
Examples
Basic Operations
import CSV from '@doeixd/csv-utils';
interface User { id: string; name: string; role: string; department?: string; accessLevel?: string; }
// Create from data
const users = CSV.fromData<User>([
{ id: '1', name: 'Alice', role: 'admin' },
{ id: '2', name: 'Bob', role: 'user' },
{ id: '3', name: 'Charlie', role: 'user' }
]);
// Query operations
const admin = users.findRow('1', 'id');
const allUsers = users.findRowsWhere(user => user.role === 'user');
// Transformation
const withDepartment = users.update({ department: 'IT' });
const updatedUsers = users.updateWhere(
user => user.role === 'admin',
{ accessLevel: 'full' }
);
// Output as CSV string (by default, includes headers)
const csvString = users.toString();
// console.log(csvString);
// id,name,role
// 1,Alice,admin
// 2,Bob,user
// 3,Charlie,user
// Write to file
users.writeToFile('users.csv');
Custom Type Casting
Apply sophisticated type conversions beyond basic CSV parsing.
import CSV, { Caster, CSVReadOptions } from '@doeixd/csv-utils';
interface Order {
order_id: string;
discount_code: string | null; // Can be 'N/A' or empty
tax_rate: number; // e.g., '7.5%' -> 0.075
created_at: Date; // e.g., '12/25/2023' -> Date object
price: number; // e.g., '$19.99' or '19.99'
}
// Custom caster for percentages (e.g., '7.5%' -> 0.075)
const percentageCaster: Caster<number> = {
test: (value) => typeof value === 'string' && value.endsWith('%'),
parse: (value) => parseFloat(value.replace('%', '')) / 100,
};
// Custom caster for dates (e.g., 'MM/DD/YYYY')
const dateCaster: Caster<Date> = {
test: (value) => typeof value === 'string' && /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(value),
parse: (value) => {
const [month, day, year] = value.split('/').map(Number);
return new Date(year, month - 1, day); // Month is 0-indexed
},
};
// Custom caster for potentially null string values
const nullableStringCaster: Caster<string | null> = {
test: (value) => typeof value === 'string' && (value.toUpperCase() === 'N/A' || value.trim() === ''),
parse: () => null,
};
const readOptions: CSVReadOptions<Order> = {
customCasts: {
definitions: { // Globally available casters by key
number: {
test: (value) => typeof value === 'string' && !isNaN(parseFloat(value.replace(/[^0-9.-]+/g, ""))),
parse: (value) => parseFloat(value.replace(/[^0-9.-]+/g, "")),
},
date: dateCaster, // Use our custom dateCaster
nullableString: nullableStringCaster,
},
columnCasts: { // Column-specific rules
order_id: 'string', // Use built-in string caster (or keep as is if already string)
discount_code: ['nullableString'], // Try nullableString caster first
tax_rate: [percentageCaster, 'number'], // Try percentage, then general number
created_at: 'date',
price: [ // Try multiple specific casters for price
{ // Caster for '$XX.YY' format
test: (v) => typeof v === 'string' && v.startsWith('$'),
parse: (v) => parseFloat(v.substring(1)),
},
'number', // Fallback to general number caster
],
},
onCastError: 'error', // 'error' (default), 'null', or 'original'
},
};
// Assuming 'orders.csv' contains:
// order_id,discount_code,tax_rate,created_at,price
// ORD001,NA,7.5%,12/25/2023,$19.99
// ORD002,,5%,01/15/2024,25
const orders = CSV.fromFile<Order>('orders.csv', readOptions);
const firstOrder = orders.toArray()[0];
console.log(firstOrder.tax_rate); // 0.075
console.log(firstOrder.created_at instanceof Date); // true
console.log(firstOrder.price); // 19.99
console.log(firstOrder.discount_code); // null
Header Mapping
Transform CSV column names to/from nested object properties.
Basic Mapping
import { createHeaderMapFns, HeaderMap } from '@doeixd/csv-utils';
interface User {
id: string;
profile: { firstName: string; lastName: string; };
contact: { email: string; };
}
// Define a mapping: CSV header -> object path
const headerMap: HeaderMap<User> = {
'user_id': 'id',
'first_name': 'profile.firstName',
'last_name': 'profile.lastName',
'email_address': 'contact.email',
};
// Create mapping functions
const { fromRowArr, toRowArr } = createHeaderMapFns<User>(headerMap);
// Convert CSV row (object) to structured object
const csvRow = {
user_id: '123',
first_name: 'John',
last_name: 'Doe',
email_address: 'john@example.com',
};
const userObject = fromRowArr(csvRow);
console.log(userObject.profile.firstName); // John
// Convert structured object back to a flat array for CSV writing
const csvHeaders = ['user_id', 'first_name', 'last_name', 'email_address'];
const flatArray = toRowArr(userObject, csvHeaders);
console.log(flatArray); // ['123', 'John', 'Doe', 'john@example.com']
Reading and Writing with Header Mapping
import CSV, { HeaderMap } from '@doeixd/csv-utils';
interface User {
id: string;
profile: { firstName: string; lastName: string; };
}
// --- READING (flat CSV columns -> nested object properties) ---
const inputHeaderMap: HeaderMap<User> = {
'USER_IDENTIFIER': 'id',
'GIVEN_NAME': 'profile.firstName',
'FAMILY_NAME': 'profile.lastName',
};
// Assumes users_input.csv has columns: USER_IDENTIFIER,GIVEN_NAME,FAMILY_NAME
const users = CSV.fromFile<User>('users_input.csv', { headerMap: inputHeaderMap });
console.log(users.toArray()[0].profile.firstName);
// --- WRITING (nested object properties -> flat CSV columns) ---
const outputHeaderMap: HeaderMap<User> = {
'id': 'UserID', // map 'id' property to 'UserID' CSV column
'profile.firstName': 'FirstName',
'profile.lastName': 'LastName',
};
users.writeToFile('users_output.csv', {
headerMap: outputHeaderMap,
stringifyOptions: { header: true } // Ensure specified headers are written
});
// users_output.csv will have columns: UserID,FirstName,LastName
Array Mapping
Map multiple CSV columns to/from an array property in your objects.
Mapping Multiple Columns to an Array
import CSV, { HeaderMap, CsvToArrayConfig } from '@doeixd/csv-utils';
interface Product {
id: string;
name: string;
imageUrls: string[];
}
// CSV columns 'image_1', 'image_2', ... map to 'imageUrls' array
const productHeaderMap: HeaderMap<Product> = {
'product_sku': 'id',
'product_name': 'name',
// This special key (e.g., '_imageMapping') is a config, not a CSV column.
'_imageMappingConfig': {
_type: 'csvToTargetArray',
targetPath: 'imageUrls', // Property in Product interface
sourceCsvColumnPattern: /^image_url_(\d+)$/, // Matches 'image_url_1', 'image_url_2', etc.
// Optional: sort columns before adding to array (e.g., by the number in pattern)
sortSourceColumnsBy: (match) => parseInt(match[1], 10),
// Optional: transform each value before adding to array
transformValue: (value) => (value ? `https://cdn.example.com/${value}` : null),
// Optional: filter out null/empty values after transformation
filterEmptyValues: true,
} as CsvToArrayConfig,
};
// Assuming products_images.csv:
// product_sku,product_name,image_url_2,image_url_1
// SKU001,Awesome Gadget,gadget_thumb.jpg,gadget_main.jpg
const products = CSV.fromFile<Product>('products_images.csv', { headerMap: productHeaderMap });
// products.toArray()[0].imageUrls will be ['https://cdn.example.com/gadget_main.jpg', 'https://cdn.example.com/gadget_thumb.jpg']
Explicit Column List for Array Mapping