How to read a CSV file in JavaScript
Short answer
For simple files, split the text into lines and each line by commas. The first line holds the column names:
const csv = 'name,city,age\nAnna,Rome,30\nOleg,Paris,25';
const [header, ...rows] = csv.split('\n').map((line) => line.split(','));
const people = rows.map((row) => Object.fromEntries(header.map((key, i) => [key, row[i]])));
console.log(people[1].city);
console.log(JSON.stringify(people[0]));Output:
Paris
{"name":"Anna","city":"Rome","age":"30"}From a file in Node.js
Read the file and apply the same parsing:
import { readFile, writeFile } from 'node:fs/promises';
await writeFile('prices.csv', 'item,price\ntea,3.5\ncake,4\n');
const lines = (await readFile('prices.csv', 'utf8')).trim().split(/\r?\n/);
const total = lines.slice(1).reduce((sum, line) => sum + Number(line.split(',')[1]), 0);
console.log(total);Output:
7.5Values in quotes
Values with commas are wrapped in quotes. A regular expression can take a quoted value as a whole:
const parseLine = (line) =>
[...line.matchAll(/"((?:[^"]|"")*)"|([^,]+)|(?<=,|^)(?=,|$)/g)].map((m) =>
m[1] !== undefined ? m[1].replaceAll('""', '"') : m[2] ?? '',
);
console.log(parseLine('Anna,"Rome, Italy",30'));Output:
[
"Anna",
"Rome, Italy",
"30"
]Common mistake
A plain split(',') breaks values that contain commas. For real files with quotes and line breaks inside values, use a ready CSV library.
console.log('Anna,"Rome, Italy",30'.split(',').length);Output:
4Functions used in this recipe
- String.prototype.split — Splits a string into an array by a separator.
- Array.prototype.map — Creates a new array by transforming every element.