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★ 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
Установить csv-parse в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
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), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic