csv-parser-node
v1.0.0
Published
A lightweight, zero-dependency Node.js CSV parser supporting file streaming for large files and Express middleware.
Maintainers
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.
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.
- Fast In-Memory Path: Files under 100 MiB are read asynchronously with
- Express Middleware Support: Plug directly into Express apps (
app.use(csvParser)) to parse incomingtext/csvHTTP request bodies intoreq.body. - RFC 4180 Compliant Parsing:
- Handles commas inside quoted fields (
"New Delhi, India"). - Handles escaped double quotes (
""->"). - Handles multi-line fields (embedded
\nor\r\ninside 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.
- Handles commas inside quoted fields (
- 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,MumbaiOutput:
[
{ 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 ArrayMemory 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 tofinalDatacontaining 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-Typeistext/csv,application/csv, ortext/x-csv. - Sets
req.bodyto the parsed array of objects. - Calls
next()on success, ornext(err)on error. - Requests with non-CSV content types pass through without modification.
- Request Size Limit: Configurable via
limitoption (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 testTest 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:
- Log in to npm:
npm login - Verify package content:
npm pack --dry-run - Publish:
(If publishing under a scoped name likenpm publish@username/csv-parser, add--access public).
License
MIT © Abhigyan Ganguly
