DEV Community

zuan peng
zuan peng

Posted on Edited on AI-assisted

Cleaning Messy CSV Data with TypeScript: A Practical Pipeline

Cleaning Messy CSV Data with TypeScript: A Practical Pipeline

Real-world CSV files are never the tidy rectangles you see in tutorials. In my client work, the files that arrive from partners, CRMs, and legacy exports routinely contain quoted commas, stray whitespace, three different date formats in one column, duplicate rows, empty trailing lines, and the occasional spreadsheet formula that somebody pasted as text. The parsing itself is the easy part. The valuable work is building a pipeline that expects the mess: validates every row, reports exactly what it fixed or rejected, and never silently drops data.

This article builds that pipeline in TypeScript 5 on Node.js 20. The input is a customer export; the output is a clean, typed JSON array plus an audit report. I will walk through the complete script, the edge cases that matter, and how I test each stage so the pipeline stays trustworthy when the next export arrives in a slightly different shape.

The Shape of the Problem

Here is a representative input file, customers-raw.csv. It is small enough to read, and it contains at least one instance of every problem I see in production files:

 id , email , name , signup_date , plan , balance
1, Alice@Example.com ,Alice Smith,2024-01-05,Pro,"1,250.00"
2,bob@example.com,Bob Jones,05/02/2024,free,0
2,bob@example.com,Bob Jones,05/02/2024,free,0
3,,Carol White,2024-03-15,Pro,300.50
4,dan@example.com,"Dan ""The Man"" Brown",15-Mar-2024,pro,-25
5,eve@example.com,Eve Davis,not-a-date,Pro,abc
6,frank@example.com,Frank Miller,2024-06-01,,150

Enter fullscreen mode Exit fullscreen mode

The defects, row by row:

  • The header has padded column names (" id ", " email ").
  • Row 1: uppercase email domain, padded fields, and a balance with a thousands separator inside quotes ("1,250.00").
  • Row 2 appears twice — an exact duplicate.
  • Row 3 has no email; for a customer record, that row cannot be used.
  • Row 4 has an escaped quote inside a quoted name and a lowercase plan value.
  • Row 5 has an unparseable date and a non-numeric balance.
  • Row 6 has an empty plan, which should fall back to a default rather than fail.
  • The file ends with a blank line.

A robust pipeline separates three concerns: parse (text → rows), normalize and validate (rows → typed records, or explicit rejections), and report (what happened to every input row). Keeping those stages separate is what makes the edge cases manageable and testable.

Step 1: Parse Without Writing Your Own CSV Parser

The single most consequential decision in a CSV pipeline is refusing to split on commas by hand. Quoting rules, escaped quotes, and embedded newlines make a hand-rolled splitter wrong in ways you discover one production incident at a time. I use csv-parse, the parser from the long-maintained csv package family:

npm init -y
npm install csv-parse
npm install -D typescript @types/node tsx
Enter fullscreen mode Exit fullscreen mode

For a batch-cleaning job, the synchronous API is the right tool: the whole file is read once, transformed, and written out. (For files in the hundreds of megabytes, switch to the streaming API with the same options — the validation code below does not change.)

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

export function parseCsv(text: string): Record<string, string>[] {
  return parse(text, {
    columns: (header: string[]) => header.map((h) => h.trim().toLowerCase()),
    skip_empty_lines: true,
    trim: true,
    relax_column_count: true,
  }) as Record<string, string>[];
}
Enter fullscreen mode Exit fullscreen mode

Three options do heavy lifting here. columns as a function lets me normalize header names — trimming the padding and lowercasing — so downstream code can rely on row.email instead of row[" email "]. trim: true strips padding from unquoted fields. relax_column_count: true tolerates rows with missing trailing cells instead of aborting the whole file; those rows surface as validation errors later, with row numbers, which is far more useful than a parser crash on line 4,000.

Step 2: Normalize and Validate Row by Row

Each field gets a small, single-purpose normalizer. Small functions are easy to unit-test, and when a client asks "why was this row rejected?" the answer points at one function.

export interface Customer {
  id: number;
  email: string;
  name: string;
  signupDate: string; // ISO yyyy-mm-dd
  plan: "free" | "pro";
  balance: number;
}

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export function normalizeEmail(raw: string): string {
  return raw.trim().toLowerCase();
}

export function parseBalance(raw: string): number {
  const cleaned = raw.replace(/[$,\s]/g, "");
  if (cleaned === "") return 0;
  const value = Number(cleaned);
  if (!Number.isFinite(value)) {
    throw new Error(`invalid balance: "${raw}"`);
  }
  return value;
}

export function parseDate(raw: string): string {
  const s = raw.trim();
  // Already ISO?
  if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;
  // dd/mm/yyyy
  const dmy = s.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
  if (dmy) return `${dmy[3]}-${dmy[2]}-${dmy[1]}`;
  // dd-Mon-yyyy
  const months: Record<string, string> = {
    jan: "01", feb: "02", mar: "03", apr: "04", may: "05", jun: "06",
    jul: "07", aug: "08", sep: "09", oct: "10", nov: "11", dec: "12",
  };
  const dmon = s.match(/^(\d{2})-([A-Za-z]{3})-(\d{4})$/);
  if (dmon) {
    const month = months[dmon[2].toLowerCase()];
    if (month) return `${dmon[3]}-${month}-${dmon[1]}`;
  }
  throw new Error(`unrecognized date: "${raw}"`);
}

export function parsePlan(raw: string): "free" | "pro" {
  const s = raw.trim().toLowerCase();
  if (s === "") return "free"; // documented default for missing plan
  if (s === "free" || s === "pro") return s;
  throw new Error(`unknown plan: "${raw}"`);
}
Enter fullscreen mode Exit fullscreen mode

A design note on parseDate: I deliberately match a closed list of formats instead of handing the string to new Date(...). JavaScript's built-in date parsing accepts a surprising range of inputs, interprets some of them in the local timezone, and happily "repairs" others — new Date("2024-02-30") does not fail, it rolls over to March 1. In a cleaning pipeline, silent repair is worse than an explicit rejection, because the repaired value looks legitimate in every downstream report. A closed format list rejects "not-a-date" and February 30 alike (the latter fails the final validity check in the row converter below), and adding a new format later is a one-line, reviewable change.

The row converter ties the normalizers together. Crucially, it does not throw on the first bad row and abandon the file. It returns a discriminated result so the pipeline can collect all problems in one run:

export type RowResult =
  | { ok: true; value: Customer }
  | { ok: false; rowNumber: number; reason: string };

export function convertRow(
  row: Record<string, string>,
  rowNumber: number,
): RowResult {
  try {
    const id = Number(row.id);
    if (!Number.isInteger(id) || id <= 0) {
      throw new Error(`invalid id: "${row.id}"`);
    }
    const email = normalizeEmail(row.email ?? "");
    if (!EMAIL_RE.test(email)) {
      throw new Error(`invalid email: "${row.email}"`);
    }
    const name = (row.name ?? "").trim();
    if (name === "") throw new Error("missing name");

    const signupDate = parseDate(row.signup_date ?? "");
    // Reject impossible dates such as 2024-02-30 that pass the format check.
    const d = new Date(`${signupDate}T00:00:00Z`);
    if (Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== signupDate) {
      throw new Error(`impossible date: "${row.signup_date}"`);
    }

    return {
      ok: true,
      value: {
        id,
        email,
        name,
        signupDate,
        plan: parsePlan(row.plan ?? ""),
        balance: parseBalance(row.balance ?? ""),
      },
    };
  } catch (err) {
    return {
      ok: false,
      rowNumber,
      reason: err instanceof Error ? err.message : String(err),
    };
  }
}
Enter fullscreen mode Exit fullscreen mode

Row numbers deserve one comment: I count data rows starting at 2, so the reported number matches the line a human sees when they open the file in an editor (line 1 is the header). Off-by-one row numbers in rejection reports waste more client time than almost any other small bug in these pipelines.

Step 3: Deduplicate With a Stated Rule

Duplicates are a policy question before they are a code question. For customer exports my default rule is: exact duplicates (same id and same email after normalization) are dropped and counted; rows that share an id but disagree on other fields are conflicts and are reported, not silently resolved — disagreeing data usually means two source systems overwrote each other, and a human should see that.

export function dedupe(customers: Customer[]): {
  unique: Customer[];
  duplicatesRemoved: number;
} {
  const seen = new Map<number, Customer>();
  let duplicatesRemoved = 0;
  for (const c of customers) {
    const existing = seen.get(c.id);
    if (!existing) {
      seen.set(c.id, c);
    } else if (existing.email === c.email) {
      duplicatesRemoved++;
    } else {
      throw new Error(
        `conflicting rows for id ${c.id}: "${existing.email}" vs "${c.email}"`,
      );
    }
  }
  return { unique: [...seen.values()], duplicatesRemoved };
}
Enter fullscreen mode Exit fullscreen mode

Whatever rule you choose, write it in the report. "3 duplicates removed" with no stated rule invites the client to wonder which three.

Step 4: The Main Script and the Audit Report

import { readFileSync, writeFileSync } from "node:fs";
import { parseCsv, convertRow, dedupe, type Customer, type RowResult } from "./pipeline.js";

function main(inputPath: string, outputPath: string): void {
  const text = readFileSync(inputPath, "utf8");
  const rows = parseCsv(text);

  const accepted: Customer[] = [];
  const rejected: RowResult[] = [];
  rows.forEach((row, i) => {
    const result = convertRow(row, i + 2); // +2: header line + 1-based
    if (result.ok) accepted.push(result.value);
    else rejected.push(result);
  });

  const { unique, duplicatesRemoved } = dedupe(accepted);
  unique.sort((a, b) => a.id - b.id);
  writeFileSync(outputPath, JSON.stringify(unique, null, 2) + "\n", "utf8");

  console.log(`Input rows:        ${rows.length}`);
  console.log(`Accepted:          ${unique.length}`);
  console.log(`Duplicates removed: ${duplicatesRemoved}`);
  console.log(`Rejected:          ${rejected.length}`);
  for (const r of rejected) {
    if (!r.ok) console.log(`  line ${r.rowNumber}: ${r.reason}`);
  }
}

main(process.argv[2] ?? "customers-raw.csv", process.argv[3] ?? "customers-clean.json");
Enter fullscreen mode Exit fullscreen mode

(The code is split across pipeline.ts and clean.ts here; run it with npx tsc and Node, or directly with npx tsx clean.ts customers-raw.csv customers-clean.json.)

Against our sample file, the report reads:

Input rows:         7
Accepted:           4
Duplicates removed: 1
Rejected:           2
  line 5: invalid email: ""
  line 7: unrecognized date: "not-a-date"
Enter fullscreen mode Exit fullscreen mode

And customers-clean.json contains exactly the four salvageable records: Alice (email lowercased, balance 1250 parsed from "1,250.00"), Bob (date normalized from 05/02/2024 to 2024-02-05), Dan (escaped quote preserved in his name, plan normalized to pro, balance -25), and Frank (missing plan defaulted to free). Every input row is accounted for: 4 accepted + 1 duplicate + 2 rejected = 7. That arithmetic check — accepted plus rejected plus duplicates equals input — is the pipeline's most important property. If the numbers ever stop adding up, something is being silently dropped, and the run should be treated as failed even if the output file looks plausible.

Testing Each Stage

Because the stages are separate functions, each gets focused tests with node:test:

  • Normalizers. Table-driven cases for each function: parseBalance("1,250.00") → 1250, parseBalance("") → 0, parseBalance("abc") throws; parseDate for each supported format plus "2024-02-30" and "not-a-date" rejections; parsePlan("") → "free".
  • Row conversion. One fixture row per known defect from real files. When a new defect appears in production, its row becomes a fixture before the fix — that habit is what turns a one-off cleanup script into a maintained pipeline.
  • End to end. Run the whole script against the sample CSV above and snapshot the report counts and the JSON output. This catches integration surprises, like a parser option change, that unit tests cannot see.
  • The accounting invariant. A property-style test: generate a few hundred random-ish rows (valid, invalid, duplicated), run the pipeline, and assert accepted + rejected + duplicates === input every time.

Where to Take It Next

Once the batch version is trusted, the usual extensions are straightforward: swap the synchronous parser for the streaming API when files grow past comfortable memory; emit the rejection list as its own CSV so clients can fix source data in a spreadsheet instead of reading console output; and add a schema check on the header so a renamed column fails loudly on line 1 rather than producing 10,000 "invalid email" rejections. Each of those is an afternoon's work because the stages were kept separate from the start.

Messy input is not an anomaly to be handled once — it is the permanent condition of data that comes from other people's systems. A pipeline that validates every row, states its rules, and accounts for every record turns each new export from a small crisis into a routine run with a readable report.


zuan peng is a JavaScript and TypeScript developer who builds data-cleaning and automation tooling for small teams. Every engagement includes human review of the final code before delivery.

Top comments (0)