From Text to Data: Lines, CSV and JSON Files
A file arrives as one long string, so a Node program splits CSV text into lines and fields, turns numbers from text into numbers, skips blank lines and reports bad rows, and reads and writes JSON files with JSON.parse and JSON.stringify.
Apprentice · Node.js · JavaScript · Updated
After this lesson you can
- Turn a CSV file's text into an array of objects, skipping blank lines and reporting bad rows
- Read and write JSON files with JSON.parse and JSON.stringify
Key takeaways
- A file's text is one long string. split("\n") cuts it into lines, and trim() on each line removes the \r a file saved on Windows leaves at the end.
- A CSV file's first line is usually its header, and split(",") cuts every other line into fields, in the header's order.
- Every field is text, so turn numbers into numbers with Number(). Number("four") is NaN, and Number("") is 0, so check a row before you trust it.
- JSON.stringify(data, null, 2) writes readable JSON to save in a file, and JSON.parse turns a JSON file's text back into data.
- split(",") breaks on a comma inside quotes, so for CSV files from other programs, such as a bank's export, use a CSV package.
Spreadsheets, banks, fitness apps and school systems all export their data as text files, most often CSV (read "C-S-V", comma-separated values) or JSON. Any time you write a tool that does something with someone else's data, such as the Expense Tracker at the end of this module, the first job is turning that text into data your code can add up.
readFile hands back Dana's whole log as one long string, and a string can't be added up. Here's what happens when you try with two of the miles, "4.0" and "3.1":
console.log("4.0" + "3.1");
4.03.1
+ glued the two pieces of text together. Before the club can total anything, the text has to become data: an array of runs, each with real numbers.
Lines and fields: split
split cuts a string at every place a separator appears and gives back the pieces as an array. Cut at "\n" (read "new line"), and each line of the file becomes one item:
const text = "date,runner,miles,minutes\n2026-11-02,Maya,4.0,38\n2026-11-02,Leo,3.1,31\n";
const lines = text.split("\n");
console.log(lines);
[
'date,runner,miles,minutes',
'2026-11-02,Maya,4.0,38',
'2026-11-02,Leo,3.1,31',
''
]
The last item is empty: the file ends with a new line, and there's nothing after it. A file saved on Windows also ends each line with \r\n (a carriage return, then a new line), so trim() each line to remove the \r, then drop the empty ones. The first line is the header: the names of the fields, in order. Split every other line at its commas:
import { readFile } from "node:fs/promises";
const text = await readFile("runs.csv", "utf8");
const lines = text.split("\n").map((line) => line.trim()).filter((line) => line !== "");
const [header, ...rows] = lines;
const runs = rows.map((row) => {
const [date, runner, miles, minutes] = row.split(",");
return { date, runner, miles: Number(miles), minutes: Number(minutes) };
});
console.log(runs);
console.log(runs[0].miles + runs[1].miles);
[
{ date: '2026-11-02', runner: 'Maya', miles: 4, minutes: 38 },
{ date: '2026-11-02', runner: 'Leo', miles: 3.1, minutes: 31 },
{ date: '2026-11-03', runner: 'Priya', miles: 5, minutes: 45 },
{ date: '2026-11-04', runner: 'Maya', miles: 6.2, minutes: 60 }
]
7.1
const [header, ...rows] = lines is array destructuring: header gets the first line, and ...rows (read "the rest") gets every line after it, as a new array. Number() turns the text "4.0" into the number 4, and now + adds.
Numbers from text, and rows that don't fit
People type logs by hand, and mistakes get in. Number() handles some text better than other text:
console.log(Number("4.0"));
console.log(Number(" 6.2 "));
console.log(Number("four"));
console.log(Number(""));
4
6.2
NaN
0
NaN (read "not a number") is what Number gives for text it can't read. The empty text is the sneaky one: it becomes 0, so a run with no miles typed in would count as a run of zero miles. Check each row before you trust it, and say which line is wrong, so Dana knows what to fix:
const text = "date,runner,miles,minutes\n2026-11-02,Maya,4.0,38\n2026-11-03,Priya,five,45\n2026-11-04,Leo,3.1\n\n2026-11-05,Maya,6.2,60\n";
const runs = [];
const lines = text.split("\n");
for (let i = 1; i < lines.length; i++) {
const line = lines[i].trim();
if (line === "") {
continue;
}
const fields = line.split(",");
const miles = Number(fields[2]);
const minutes = Number(fields[3]);
if (fields.length !== 4 || Number.isNaN(miles) || Number.isNaN(minutes)) {
console.log(`Skipping line ${i + 1}: ${line}`);
continue;
}
runs.push({ date: fields[0], runner: fields[1], miles, minutes });
}
console.log(`${runs.length} runs read`);
Skipping line 3: 2026-11-03,Priya,five,45
Skipping line 4: 2026-11-04,Leo,3.1
2 runs read
Number.isNaN(x) answers true when x is NaN. Line numbers count from 1, the way an editor shows them, so line i of the array is line i + 1 of the file.
JSON files
A CSV file suits a table of runs. For anything with more shape, such as a summary or a program's settings, save JSON. JSON.stringify(data, null, 2) writes it with two-space indents, so a person can read the file too, and JSON.parse turns the file's text back into data:
import { readFile, writeFile } from "node:fs/promises";
const summary = { runner: "Maya", week: "2026-11-02", runs: 2, miles: 10.2 };
await writeFile("summary.json", JSON.stringify(summary, null, 2));
const saved = JSON.parse(await readFile("summary.json", "utf8"));
console.log(saved.miles + 4.3);
console.log(await readFile("summary.json", "utf8"));
14.5
{
"runner": "Maya",
"week": "2026-11-02",
"runs": 2,
"miles": 10.2
}
The numbers come back as numbers, which is JSON's advantage over CSV. When a JSON file is damaged, JSON.parse throws a SyntaxError, as JSON: Data You Can Save and Send shows; catch it, as you catch ENOENT.
Where a CSV package fits
split(",") works for files you write yourself. Files from other programs bring a catch: a field that holds a comma is wrapped in quotes, and split doesn't know that.
const line = '2026-11-08,Maya,"Trail run, hilly",5.5';
console.log(line.split(","));
[ '2026-11-08', 'Maya', '"Trail run', ' hilly"', '5.5' ]
Five fields instead of four. For CSV files you don't control, such as a bank's export, an npm package that reads CSV properly (csv-parse is a common one) handles quotes, commas inside them and quotes inside those.
Do it: turn the club's log into runs
Dana pastes runs into the log by hand, and some of her lines are wrong. Write the function that reads the log's text and keeps only the runs it can trust.
Your job: write readRuns(text).
text: the log's whole text. Its first line is the header,date,runner,miles,minutes, and every line after it is one run.- Return an array with one object per good run, in the text's order:
{ date, runner, miles, minutes }, withmilesandminutesas numbers. - Skip blank lines.
- Skip a bad line: one that doesn't have exactly 4 fields, or whose miles or minutes isn't a number.
- A log with only its header gives an empty array,
[].
Worked through: for "date,runner,miles,minutes\n2026-11-02,Maya,4.0,38\n2026-11-02,Leo,3.1,31\n", the two lines under the header are good runs, so readRuns returns [{ date: "2026-11-02", runner: "Maya", miles: 4, minutes: 38 }, { date: "2026-11-02", runner: "Leo", miles: 3.1, minutes: 31 }].
Practiced live on the lesson page: write the JavaScript right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
Every file a program reads arrives as text: split it, check it and turn it into numbers, or save it as JSON, and someone's data becomes something your code can total, sort and report.