Package Exports
- vsc-parser
Readme
vsc-parser
A powerful VSC (Values Separated by Commas) parser for TypeScript/JavaScript 🚀
Parse VSC/CSV data into structured JavaScript objects for easy manipulation and processing in your code. Optimized for production use with full TypeScript support and zero dependencies.
What is VSC?
VSC (Values Separated by Commas) is a common data format where values are separated by delimiters (commas, tabs, semicolons, etc.). This parser transforms raw VSC text into structured JavaScript objects that you can easily work with in your code.
Why vsc-parser?
🎯 Developer-Friendly API
- Clean Output: Converts VSC rows into JavaScript objects with named properties
- Type-Safe: Full TypeScript definitions for autocomplete and type checking
- Easy Integration: Simple API - just pass a string, get structured data back
⚡ Performance & Reliability
- Zero Dependencies: Pure Node.js implementation, no external libraries needed
- Production-Ready: Comprehensive test coverage with 29 test cases
- Fast Parsing: Efficient character-by-character parsing with minimal overhead
🛠️ Flexible Configuration
- Custom Delimiters: Support for comma, semicolon, tab, pipe, or any single character
- Quote Handling: Properly handles quoted fields containing delimiters and newlines
- Configurable Options: Trim whitespace, skip empty lines, custom headers, and more
- Robust Error Handling: Clear error messages with position tracking
Installation
npm install vsc-parserQuick Start
import { parse } from "vsc-parser";
// Parse VSC data into JavaScript objects
const vscData = `name,age,city
John,30,NYC
Jane,25,SF`;
const result = parse(vscData);
// Access parsed data as objects
console.log(result.data);
// [
// { name: 'John', age: '30', city: 'NYC' },
// { name: 'Jane', age: '25', city: 'SF' }
// ]
// Work with the data in your code
result.data.forEach((person) => {
console.log(
`${person.name} is ${person.age} years old and lives in ${person.city}`
);
});
// Access metadata
console.log(result.headers); // ['name', 'age', 'city']
console.log(result.rowCount); // 2Advanced Usage
Custom Delimiters
Perfect for parsing tab-separated or pipe-delimited data:
// Tab-separated values
const tsvData = "name\tage\nJohn\t30";
const result = parse(tsvData, { delimiter: "\t" });
// Semicolon-separated (European VSC)
const vscData = "name;age\nJohn;30";
const result = parse(vscData, { delimiter: ";" });Handling Quoted Fields
Automatically handles complex VSC with commas and newlines in quoted fields:
const vscData = `name,address,notes
John,"123 Main St, Apt 4","Important
multi-line
notes"`;
const result = parse(vscData);
// Preserves commas and newlines within quoted fieldsWorking with Parsed Data
Once parsed, you can easily manipulate the data in your code:
const vscData = `product,price,quantity
Apple,1.50,100
Banana,0.75,200
Orange,2.00,150`;
const result = parse(vscData);
// Filter data
const expensive = result.data.filter((item) => parseFloat(item.price) > 1.0);
// Transform data
const inventory = result.data.map((item) => ({
name: item.product,
totalValue: parseFloat(item.price) * parseInt(item.quantity),
}));
// Aggregate data
const totalQuantity = result.data.reduce(
(sum, item) => sum + parseInt(item.quantity),
0
);
// Convert back to different format
const jsonOutput = JSON.stringify(result.data, null, 2);Error Handling
import { parse, ParseError } from "vsc-parser";
try {
const result = parse(vscData);
// Process result
} catch (error) {
if (error instanceof ParseError) {
console.error(
`Parse error at position ${error.position}: ${error.message}`
);
}
}API Reference
parse(data: string, options?: ParseOptions): ParseResult
Parses VSC string data into structured objects.
Parameters
data(string): The VSC string to parseoptions(ParseOptions, optional): Configuration optionsdelimiter(string): Field delimiter character (default:',')quote(string): Quote character for escaping (default:'"')hasHeaders(boolean): Treat first row as headers (default:true)trim(boolean): Trim whitespace from values (default:false)skipEmptyLines(boolean): Skip empty lines (default:true)
Returns
ParseResult: Object containing:data(VscRow[]): Array of parsed row objectsheaders(string[]): Column headersrowCount(number): Number of data rows (excluding header)
Throws
ParseError: When parsing fails, includes position information
Types
type VscRow = Record<string, string>;
interface ParseResult {
data: VscRow[];
headers: string[];
rowCount: number;
}
interface ParseOptions {
delimiter?: string;
quote?: string;
skipEmptyLines?: boolean;
hasHeaders?: boolean;
trim?: boolean;
}
class ParseError extends Error {
position?: number;
}Common Use Cases
1. Import Data from Files
import { readFileSync } from "fs";
const vscContent = readFileSync("data.csv", "utf-8");
const parsed = parse(vscContent);
// Now use parsed.data in your application
saveToDatabase(parsed.data);2. API Response Processing
// Process VSC data from API responses
const response = await fetch("https://api.example.com/data.csv");
const vscText = await response.text();
const result = parse(vscText);
// Work with structured data
const formatted = result.data.map((row) => ({
id: parseInt(row.id),
name: row.name,
active: row.status === "active",
}));3. Data Transformation Pipelines
// Transform VSC to different formats
const vscData = loadVscFile();
const parsed = parse(vscData);
// Filter and transform
const processed = parsed.data
.filter((row) => row.status === "active")
.map((row) => ({
...row,
timestamp: new Date(row.date).getTime(),
}));
// Export to JSON, database, or other formats
exportToJson(processed);Development
Install dependencies
npm installRun tests
npm testRun tests with coverage
npm run test:coverageRun tests with UI
npm run test:uiBuild
npm run buildLint
npm run lintFormat
npm run formatCheck (lint + format)
npm run checkScripts
npm run dev- Start development modenpm run build- Build the librarynpm test- Run tests in watch modenpm run test:coverage- Run tests with coverage reportnpm run test:ui- Run tests with Vitest UInpm run lint- Lint the code with Biomenpm run lint:fix- Lint and fix issues with Biomenpm run format- Format code with Biomenpm run format:check- Check code formatting with Biomenpm run check- Run all Biome checks (lint + format)npm run check:fix- Run all Biome checks and fix issuesnpm run typecheck- Run TypeScript type checking
License
The Unlicense - Public Domain
This software is released into the public domain. You can copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.