or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

errors.mdindex.mdoptions.mdstreaming.mdsync.md
tile.json

sync.mddocs/

Synchronous API

The synchronous API provides immediate CSV parsing for smaller data sets, perfect for configuration files, small data imports, and scenarios where streaming is not required.

Imports

The sync entry point exports the parse function plus all type definitions from the main module:

import { 
  parse, 
  CsvError,
  CastingContext,
  CastingFunction, 
  CastingDateFunction,
  ColumnOption,
  Options,
  OptionsNormalized,
  Info,
  CsvErrorCode
} from "csv-parse/sync";

Capabilities

Synchronous Parse Function

Parses CSV data synchronously and returns the complete result immediately. Available through the csv-parse/sync entry point.

/**
 * Synchronously parse CSV data and return complete results
 * @param input - CSV data as string, Buffer, or Uint8Array
 * @param options - Optional parsing configuration
 * @returns Parsed records as arrays or objects based on options
 */
function parse(input: Buffer | string | Uint8Array): string[][];
function parse(input: Buffer | string | Uint8Array, options: Options): string[][];
function parse<T>(input: Buffer | string | Uint8Array, options: OptionsWithColumns<T>): T[];

Usage Examples:

import { parse } from "csv-parse/sync";

// Basic parsing - returns arrays
const records = parse("name,age\nAlice,25\nBob,30");
console.log(records);
// [['name', 'age'], ['Alice', '25'], ['Bob', '30']]

// Parse with columns option - returns objects
const users = parse("name,age\nAlice,25\nBob,30", { columns: true });
console.log(users);
// [{ name: 'Alice', age: '25' }, { name: 'Bob', age: '30' }]

// Parse with custom delimiter
const tsvData = "name\tage\nAlice\t25\nBob\t30";
const tsvRecords = parse(tsvData, { 
  delimiter: "\t",
  columns: true
});
console.log(tsvRecords);
// [{ name: 'Alice', age: '25' }, { name: 'Bob', age: '30' }]

Type-Safe Parsing

When using TypeScript with columns configuration, the return type is automatically inferred.

// Type definitions for TypeScript usage
type OptionsWithColumns<T> = Omit<Options<T>, "columns"> & {
  columns: Exclude<Options["columns"], undefined | false>;
};

Usage Examples:

import { parse } from "csv-parse/sync";

// Strongly typed parsing
interface User {
  name: string;
  age: string; // CSV values are always strings initially
  active: string;
}

const csvData = "name,age,active\nAlice,25,true\nBob,30,false";
const users = parse<User>(csvData, { columns: true });

// TypeScript knows users is User[]
users.forEach(user => {
  console.log(`${user.name} is ${user.age} years old`);
});

// With type casting
const processedUsers = parse<User>(csvData, { 
  columns: true,
  cast: (value, context) => {
    if (context.column === 'age') return parseInt(value);
    if (context.column === 'active') return value === 'true';
    return value;
  }
});

Configuration File Parsing

Common patterns for parsing configuration and data files.

Usage Examples:

import { parse } from "csv-parse/sync";
import fs from "fs";

// Parse configuration file
const configCsv = fs.readFileSync("config.csv", "utf8");
const config = parse(configCsv, {
  columns: true,
  skip_empty_lines: true,
  comment: "#",
  trim: true
});

// Parse with data transformation
const products = parse(fs.readFileSync("products.csv"), {
  columns: true,
  cast: (value, context) => {
    // Auto-convert numeric fields
    if (context.column === 'price' || context.column === 'quantity') {
      return parseFloat(value);
    }
    // Convert boolean fields
    if (context.column === 'active') {
      return value.toLowerCase() === 'true';
    }
    return value.trim();
  }
});

console.log(products);
// [
//   { name: 'Laptop', price: 999.99, quantity: 5, active: true },
//   { name: 'Book', price: 29.99, quantity: 12, active: true }
// ]

Error Handling

Synchronous parsing throws CsvError instances for any parsing failures.

Usage Examples:

import { parse, CsvError } from "csv-parse/sync";

try {
  // This will throw due to inconsistent column count
  const records = parse("name,age\nAlice,25,extra", {
    columns: true,
    relax_column_count: false
  });
} catch (err) {
  if (err instanceof CsvError) {
    console.error("CSV parsing error:", err.code);
    console.error("Message:", err.message);
    console.error("Line:", err.lines);
    console.error("Column:", err.column);
  } else {
    console.error("Unexpected error:", err);
  }
}

// Graceful error handling with relaxed parsing
try {
  const records = parse("name,age\nAlice,25\nBob,30,Boston", {
    columns: true,
    relax_column_count: true, // Allow inconsistent column counts
    skip_empty_lines: true
  });
  console.log("Successfully parsed:", records.length, "records");
} catch (err) {
  console.error("Failed to parse CSV:", err.message);
}

Advanced Synchronous Usage

Complex parsing scenarios with custom options and data processing.

Usage Examples:

import { parse } from "csv-parse/sync";

// Custom column mapping
const csvData = `
# Customer data export
customer_id,full_name,email_address,registration_date
001,Alice Johnson,alice@example.com,2023-01-15
002,Bob Smith,bob@example.com,2023-02-20
`;

const customers = parse(csvData, {
  columns: (header) => {
    // Custom column name mapping
    return header.map(name => {
      switch (name) {
        case 'customer_id': return 'id';
        case 'full_name': return 'name';
        case 'email_address': return 'email';
        case 'registration_date': return 'registered';
        default: return name;
      }
    });
  },
  comment: '#',
  skip_empty_lines: true,
  cast: (value, context) => {
    // Parse dates
    if (context.column === 'registered') {
      return new Date(value);
    }
    return value;
  }
});

console.log(customers);
// [
//   { id: '001', name: 'Alice Johnson', email: 'alice@example.com', registered: Date object },
//   { id: '002', name: 'Bob Smith', email: 'bob@example.com', registered: Date object }
// ]

// Parse with record filtering and transformation
const salesData = parse(fs.readFileSync("sales.csv"), {
  columns: true,
  cast: true, // Enable automatic type casting
  on_record: (record, context) => {
    // Filter out records with zero sales
    if (parseFloat(record.amount) <= 0) {
      return undefined; // Skip this record
    }
    
    // Transform the record
    return {
      ...record,
      amount: parseFloat(record.amount),
      processed: true,
      line_number: context.lines
    };
  }
});

Memory Considerations

Best practices for using the synchronous API with larger data sets.

Usage Examples:

import { parse } from "csv-parse/sync";
import fs from "fs";

// Check file size before synchronous parsing
const stats = fs.statSync("data.csv");
const maxSyncSize = 10 * 1024 * 1024; // 10MB limit

if (stats.size > maxSyncSize) {
  console.warn("File too large for synchronous parsing, use streaming API");
  // Use streaming API instead
} else {
  const records = parse(fs.readFileSync("data.csv"), {
    columns: true,
    skip_empty_lines: true
  });
  
  console.log(`Parsed ${records.length} records synchronously`);
}

// Memory-efficient parsing with selective field extraction
const largeDataSubset = parse(fs.readFileSync("large-dataset.csv"), {
  columns: true,
  on_record: (record) => {
    // Extract only needed fields to reduce memory usage
    return {
      id: record.id,
      name: record.name,
      status: record.status
      // Skip other fields to save memory
    };
  }
});