npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

csv-parser-node

v1.0.0

Published

A lightweight, zero-dependency Node.js CSV parser supporting file streaming for large files and Express middleware.

Readme

csv-parser-node

A lightweight, robust, zero-dependency Node.js CSV parser built from scratch. Supports both asynchronous file parsing (with automated streaming for large files) and incoming CSV body parsing as Express middleware.

License: MIT Zero Dependencies Node.js


Features

  • Zero Dependencies: Built entirely with native Node.js core modules (fs, stream).
  • Dual File Processing Strategy:
    • Fast In-Memory Path: Files under 100 MiB are read asynchronously with fs.promises.readFile().
    • Large File Streaming: Files 100 MiB or larger automatically switch to streaming via fs.createReadStream(), buffering row state chunk-by-chunk.
  • Express Middleware Support: Plug directly into Express apps (app.use(csvParser)) to parse incoming text/csv HTTP request bodies into req.body.
  • RFC 4180 Compliant Parsing:
    • Handles commas inside quoted fields ("New Delhi, India").
    • Handles escaped double quotes ("" -> ").
    • Handles multi-line fields (embedded \n or \r\n inside quotes).
    • Handles Windows (\r\n) and Unix (\n) line breaks cleanly.
    • Automatically strips UTF-8 Byte Order Marks (\uFEFF).
    • Handles files with or without trailing newlines.
    • Safely skips blank lines while preserving rows containing empty fields (e.g. ,).
    • Predictable missing and extra column policies.
  • Clear Error Handling: Meaningful errors for malformed CSVs (such as unclosed quoted fields) and I/O stream failures.

Installation

npm install csv-parser-node

(Or use locally via require("./main.js"))


Quick Start

1. Parsing CSV Files on Disk

const csvParser = require("csv-parser-node");

async function parseFile() {
  try {
    const data = await csvParser("./data.csv");
    console.log(data);
  } catch (err) {
    console.error("Failed to parse CSV:", err.message);
  }
}

parseFile();

Given data.csv:

name,age,city
Rahul,20,"New Delhi, India"
Aman,21,Mumbai

Output:

[
  { name: "Rahul", age: "20", city: "New Delhi, India" },
  { name: "Aman", age: "21", city: "Mumbai" }
]

2. Express Middleware

Use csvParser directly as an Express middleware. When incoming requests have a CSV Content-Type (such as text/csv, application/csv, or text/x-csv), the middleware automatically parses the body and assigns the resulting array of objects to req.body.

const express = require("express");
const csvParser = require("csv-parser-node");

const app = express();

// Register the CSV parser middleware
app.use(csvParser);

app.post("/upload-csv", (req, res) => {
  console.log("Parsed rows:", req.body);
  res.json({
    message: "CSV received successfully",
    count: req.body.length,
    rows: req.body
  });
});

app.listen(3000, () => {
  console.log("Server listening on port 3000");
});

(Both app.use(csvParser) and app.use(csvParser()) are supported).


Edge Case Handling & Policy

| Edge Case | Behavior | Example Input | Parsed Result | | :--- | :--- | :--- | :--- | | Commas in Quotes | Preserved as a single field value | Rahul,"New Delhi, India" | city: "New Delhi, India" | | Escaped Double Quotes | Converted to a single quote (") per RFC 4180 | Aarav,"He said ""hello""" | message: 'He said "hello"' | | Embedded Newlines | Multi-line fields preserved intact across lines and chunks | "Hello\nhow are you?" | message: "Hello\nhow are you?" | | Windows CRLF (\r\n) | Cleanly stripped; no trailing \r on parsed values | Pune\r\n | city: "Pune" | | Blank Rows | Completely blank lines ("" or "\r") are skipped | \n\n | Skipped | | Empty Fields | Preserved as empty strings; rows with empty fields are never discarded | Aman,,Mumbai | { name: 'Aman', age: '', city: 'Mumbai' } | | Trailing Newline | Handled identically whether trailing newline is present or omitted | Alice,30 vs Alice,30\n | { name: 'Alice', age: '30' } | | UTF-8 BOM | Stripped from the first header column | \uFEFFname,age | { name: '...' } (not \uFEFFname) | | Missing Columns | Fields omitted in a row default to empty strings ("") | Header: 3 cols, Row: 2 cols | Missing 3rd field is "" | | Extra Columns | Extra columns are preserved in an _extra array without data loss | Header: 2 cols, Row: 3 cols | _extra: ["col3Value"] | | Unclosed Quotes | Rejects Promise or calls next(err) with a descriptive error | Aarav,"Unclosed text | Error: Malformed CSV: Unclosed quoted field | | Empty File | Resolves to an empty array | Empty file (0 bytes) | [] | | Header-only File | Resolves to an empty array | name,age,city\n | [] |


Large File Streaming & Memory Architecture

For files under 100 MiB, the file is read in its entirety using fs.promises.readFile(), which maximizes speed for standard datasets.

For files 100 MiB or larger, the parser automatically switches to Node.js streams via fs.createReadStream():

               CSV File
                  │
          Check File Size
                  │
        ┌─────────┴─────────┐
        ▼                   ▼
    < 100 MiB           >= 100 MiB
        │                   │
  readFile()          createReadStream()
        │                   │
        │             Chunk Stream Event
        │                   │
        │             Buffer Incomplete Rows
        │             across Chunks
        │                   │
        └─────────┬─────────┘
                  ▼
          Parse CSV Rows (parseRow)
                  ▼
         First Row = Header
                  ▼
      Convert Rows to Objects
                  ▼
             Return Array

Memory Considerations

  • Streaming Input Buffer: The streaming path only keeps the current incomplete row in memory buffer between stream chunks (buffer.slice(start)). It avoids loading the raw multi-gigabyte CSV file string into memory all at once.
  • In-Memory Objects Array: Because the csvParser(filePath) API returns a Promise resolving to finalData containing all parsed row objects, the returned JavaScript objects will occupy memory proportional to the number of records. (For example, 1.5 million parsed rows occupies ~200MB of heap).

API Reference

csvParser(filePath)

Parses a CSV file located at filePath.

  • Arguments: filePath (string): Absolute or relative path to the CSV file.
  • Returns: Promise<Array<Object>>: Resolves to an array of objects where keys are derived from the header row.
  • Errors: Rejects if file cannot be found, stream fails, or CSV contains unclosed quotes.

csvParser(req, res, next) (Express Middleware)

Express middleware function. Can be registered directly with app.use(csvParser) or with options app.use(csvParser({ limit: '10mb' })).

  • Reads incoming request stream if Content-Type is text/csv, application/csv, or text/x-csv.
  • Sets req.body to the parsed array of objects.
  • Calls next() on success, or next(err) on error.
  • Requests with non-CSV content types pass through without modification.
  • Request Size Limit: Configurable via limit option (default: 10MB). If exceeded, rejects with HTTP 413 (Request entity too large) to protect server memory.

csvParser.parse(csvString)

Synchronously parses an in-memory CSV string.

  • Arguments: csvString (string): Raw CSV text.
  • Returns: Array<Object>.

csvParser.parseStream(filePath)

Directly invokes the streaming parser on a file, regardless of its size.

  • Arguments: filePath (string).
  • Returns: Promise<Array<Object>>.

csvParser.parseRow(rowString)

Parses a single row string into an array of string column values, respecting quotes and escaped quotes.

  • Arguments: rowString (string).
  • Returns: Array<string>.

Testing

The package includes a comprehensive automated test suite covering all core requirements, edge cases, Express middleware endpoints, and large file streaming.

Run tests:

npm test

Test output:

Starting CSV Parser Test Suite...

✓ PASS: 1. Small file parsing with quoted commas
✓ PASS: 2A. File without trailing newline
✓ PASS: 2B. File with trailing newline
✓ PASS: 3. Windows CRLF line endings (\r\n)
✓ PASS: 4. Blank rows are skipped without discarding empty fields
✓ PASS: 5. Escaped double quotes inside quoted fields
✓ PASS: 6. Embedded newlines inside quoted fields
✓ PASS: 7A. Empty file returns empty array
✓ PASS: 7B. Header-only file returns empty array
✓ PASS: 8. Missing and extra columns policy
✓ PASS: 9. UTF-8 BOM handling
✓ PASS: 10. Malformed CSV with unclosed quotes throws error
✓ PASS: 11. Non-existent file rejects with error
✓ PASS: 12. Express middleware integration (app.use(csvParser))
✓ PASS: 13. Express middleware ignores non-CSV Content-Type
✓ PASS: 14. Express middleware error handling on malformed CSV (calls next(err))
✓ PASS: 15. Express middleware factory syntax app.use(csvParser())
✓ PASS: 16. parseStream edge cases (embedded newlines, escaped quotes, no trailing newline)
✓ PASS: 17. Large file streaming test (> 100 MiB file)

Test Results: 19/19 passed.

Publishing to npm

To publish this package to the npm registry:

  1. Log in to npm:
    npm login
  2. Verify package content:
    npm pack --dry-run
  3. Publish:
    npm publish
    (If publishing under a scoped name like @username/csv-parser, add --access public).

License

MIT © Abhigyan Ganguly