Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

csv-parse

БесплатноБез исполняемых скриптовНе проверен

Parse and generate CSV files with the csv package — stream large files, handle custom delimiters, transform records, validate data, and generate CSV output…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

csv-parse

Overview

The csv project (node-csv) is four packages: csv-parse, csv-stringify, stream-transform and csv-generate. The csv package re-exports all four. Parsers and stringifiers are Node.js streams, with a /sync entry point for small inputs and a /browser/esm build for browsers. Values come out as strings unless you ask for casting. Checked against csv-parse 7.0.3, csv-stringify 6.9.0 and stream-transform 3.6.0.

Instructions

Setup

npm install csv-parse csv-stringify stream-transform

npm install csv installs everything in one package; the examples below import from the individual packages. They are ES modules ("type": "module" in package.json), and they type-check with tsc under module: nodenext.

Parsing a CSV file

// src/csv/parse-file.ts — Read a CSV file and convert rows to objects.
// Uses the header row as keys for each record object.
import { parse } from "csv-parse";
import fs from "node:fs";

export async function parseCsvFile(filePath: string): Promise<Record<string, string>[]> {
  const records: Record<string, string>[] = [];

  const parser = fs.createReadStream(filePath).pipe(
    parse({
      columns: true,       // use first row as headers
      skip_empty_lines: true,
      trim: true,
      bom: true,           // strip the byte-order mark Excel adds to UTF-8 files
    })
  );

  for await (const record of parser) {
    records.push(record);
  }

  return records;
}

Without skip_empty_lines, a blank line at the end of the file raises CSV_RECORD_INCONSISTENT_COLUMNS. Without bom: true, the first header of a file saved by Excel starts with an invisible character, so record.name is undefined.

Parsing a CSV String

// src/csv/parse-string.ts — Parse CSV data from a string (e.g., API response body).
import { parse } from "csv-parse/sync";

export function parseCsvString(csvData: string) {
  return parse(csvData, {
    columns: true,
    skip_empty_lines: true,
    cast: true,           // numeric strings become numbers; "true" stays a string
    cast_date: true,      // date strings become Date objects
  });
}

Generating CSV Output

// src/csv/stringify.ts — Convert objects to CSV strings for download or file export.
import { stringify } from "csv-stringify/sync";

interface SalesRow {
  product: string;
  revenue: number;
  units: number;
  date: string;
}

export function generateCsv(data: SalesRow[]): string {
  return stringify(data, {
    header: true,
    columns: [
      { key: "product", header: "Product Name" },
      { key: "revenue", header: "Revenue ($)" },
      { key: "units", header: "Units Sold" },
      { key: "date", header: "Date" },
    ],
  });
}

Streaming Large Files

// src/csv/stream.ts — Process million-row CSV files without loading into memory.
// Transform each record as it streams through.
import { parse } from "csv-parse";
import { stringify } from "csv-stringify";
import { transform } from "stream-transform";
import { pipeline } from "node:stream/promises";
import fs from "node:fs";

export async function transformCsv(inputPath: string, outputPath: string) {
  // pipeline() forwards an error from any stage and closes every stream;
  // a plain .pipe() chain leaves parse errors unhandled.
  await pipeline(
    fs.createReadStream(inputPath),
    parse({ columns: true, skip_empty_lines: true, trim: true, bom: true }),
    transform((record: Record<string, string>) => ({
      name: record.name.toUpperCase(),
      email: record.email.toLowerCase(),
      total: Number(record.price) * Number(record.quantity),
    })),
    stringify({ header: true }),
    fs.createWriteStream(outputPath)
  );
}

Custom Delimiters

// src/csv/delimiters.ts — Handle TSV files, semicolon-separated, or pipe-delimited.
import { parse } from "csv-parse/sync";

// Tab-separated values
const tsvData = "name\tage\tcity\nAlice Moreau\t30\tPrague";
const tsvRecords = parse(tsvData, { columns: true, delimiter: "\t" });

// Semicolon-separated (common in European exports)
const csvData = "name;age;city\nAlice;30;Prague";
const csvRecords = parse(csvData, { columns: true, delimiter: ";" });

// Unknown delimiter: let the parser pick one from the first rows
const guessed = parse(csvData, { columns: true, delimiter_auto: true });

Use delimiter_auto only when the delimiter really is unknown. A fixed delimiter is faster and never guesses wrong.

Validation

// src/csv/validate.ts — Validate CSV records during parsing and collect errors.
import { parse } from "csv-parse";
import fs from "node:fs";

interface ValidationError {
  line: number;
  field: string;
  message: string;
}

export async function validateCsv(
  filePath: string,
  requiredFields: string[]
): Promise<{ valid: Record<string, string>[]; errors: ValidationError[] }> {
  const valid: Record<string, string>[] = [];
  const errors: V
Полный SKILL.md на GitHub

Установить csv-parse в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл csv-parse?

Parse and generate CSV files with the csv package — stream large files, handle custom delimiters, transform records, validate data, and generate CSV output from objects. Use when tasks involve data import/export, ETL pipelines, processing uploaded CSV files, or generating downloadable reports.

Как установить скилл csv-parse?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл csv-parse запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить csv-parse с