In the last lesson, you turned Dana’s expenses into JSON text with JSON.stringify() and read it back with JSON.parse(). The text only lived inside the running program, though. When the script ended, it was gone, and Dana still had to type her records into the code.
In this lesson, you’ll give that text a home. You’ll write Dana’s expenses to a file called expenses.json, load them back the next time the program runs, and convert the fields that JSON returns as strings. Start by setting up a folder for the tracker and saving the records once.
Save the Expenses to a File
A file lets data outlive a program. Node.js comes with tools for reading and writing files, and this course uses two of them as a fixed recipe that you’ll type now and come back to. You don’t need to know how they work internally.
In your terminal, make a folder for Dana’s tracker and move into it:
$ mkdir budget-tracker
$ cd budget-tracker
In your editor, create a file called package.json in that folder with this single line:
package.json
{ "type": "module" }
This file tells Node.js that the files in this folder use import. Next to it, create tracker.js with the three records you met in the last lesson:
tracker.js
import { readFileSync, writeFileSync } from "node:fs";
const expenses = [
{
date: new Date("2026-10-03"), category: "groceries",
amount: 64, note: "farmers market",
},
{
date: new Date("2026-10-05"), category: "transport",
amount: 45, note: "bus pass",
},
{
date: new Date("2026-10-09"), category: "utilities",
amount: 72, note: undefined,
},
];
const text = JSON.stringify(expenses, null, 2);
writeFileSync("expenses.json", text);
console.log("Saved", expenses.length, "expenses");
The first line borrows two ready-made functions from Node.js’s file tools. You’ll learn what import does in a later lesson, and that’s all you need to know about it for now. writeFileSync() takes a filename and a string, and it creates or replaces that file in the folder you run node from.
Run the script:
$ node tracker.js
Saved 3 expenses
Open expenses.json in your editor. It holds the same indented text you printed in the last lesson: dates as strings and no note in the third record. The data now exists outside the program.
Load the File and Fix the Types
Now that the data lives in a file, Dana can edit it without touching the code. She opens expenses.json and types a fourth record at the end of the array, after a comma, copying the shape of the others:
{
"date": "2026-10-12T00:00:00.000Z",
"category": "fun",
"amount": "38",
"note": "movie night with Malik"
}
Your file should now hold four records:
expenses.json
[
{
"date": "2026-10-03T00:00:00.000Z",
"category": "groceries",
"amount": 64,
"note": "farmers market"
},
{
"date": "2026-10-05T00:00:00.000Z",
"category": "transport",
"amount": 45,
"note": "bus pass"
},
{
"date": "2026-10-09T00:00:00.000Z",
"category": "utilities",
"amount": 72
},
{
"date": "2026-10-12T00:00:00.000Z",
"category": "fun",
"amount": "38",
"note": "movie night with Malik"
}
]
Dana puts quotes around 38, as she does for the other values she types. That’s still valid JSON, so nothing complains.
To see what reading the file gives you, start Node.js’s REPL. In the budget-tracker folder, type node and press Enter. The REPL has Node.js’s file tools ready as fs, so no import line is needed:
> const text = fs.readFileSync("expenses.json", "utf8");
undefined
> typeof text
'string'
> text.length
471
> text[0]
'['
> text[0].amount
undefined
readFileSync() takes a filename. Its second argument, "utf8", tells Node.js to read the file’s bytes as UTF-8 text, so you get a string back instead of raw bytes. text.length is 471 here, though yours may differ slightly depending on how you spaced your records. text[0] is the first character. Type .exit to leave the REPL.
Watch out: text read from a file looks like Dana’s records but is one string, so reading .amount on it gives undefined instead of an error. Use JSON.parse() to turn that text into records.
The records now live in the file, so replace the whole of tracker.js with this version. It keeps the import line, parses the text, and adds up the amounts with .reduce():
tracker.js
import { readFileSync, writeFileSync } from "node:fs";
const text = readFileSync("expenses.json", "utf8");
const expenses = JSON.parse(text);
const total = expenses.reduce(
(sum, expense) => sum + expense.amount,
0,
);
console.log("Records:", expenses.length);
console.log("Total:", total);
The four amounts are 64, 45, 72, and 38. Before you run the script, decide what total you expect it to print. Then run it with node tracker.js and compare:
$ node tracker.js
Records: 4
Total: 18138
The first three amounts add up to 181. Then sum + expense.amount meets the string "38". With a string, + joins text instead of adding, so 181 and "38" become "18138". You can confirm what JSON.parse() built by logging the types of two fields:
console.log(typeof expenses[3].amount);
console.log(typeof expenses[0].date);
Both lines print string. JSON.parse() has no idea what Dana’s fields mean. It follows the text: anything in quotes becomes a string. That’s why the dates came back as strings too, even though they started as Date objects.
The fix is to convert each field yourself, right after parsing. In tracker.js, change the JSON.parse() line so that it builds a fresh record for each expense, with Number() for the amount and new Date() for the date:
tracker.js
import { readFileSync, writeFileSync } from "node:fs";
const text = readFileSync("expenses.json", "utf8");
const expenses = JSON.parse(text).map((expense) => ({
...expense,
date: new Date(expense.date),
amount: Number(expense.amount),
}));
const total = expenses.reduce(
(sum, expense) => sum + expense.amount,
0,
);
console.log("Records:", expenses.length);
console.log("Total:", total);
Each record keeps its other properties through the spread syntax, and only date and amount are replaced. Number() is the same conversion you used in Compare and Convert, and it leaves an amount that’s already a number unchanged. Run the script again, and the total is right:
$ node tracker.js
Records: 4
Total: 219
This recipe assumes every date is a real date and every amount is a number, with or without quotes. A typo such as "oops" becomes NaN, JavaScript’s not a number value, which saves as null and reloads as 0. If a field goes bad like that, fix it by hand in expenses.json.
JSON.parse() also accepts a second argument, a reviver function that can do these conversions while it parses. You won’t need one in this course, because the .map() keeps every step visible.
If the "18138" total still puzzles you, the button below opens a mentor chat to talk through why both conversions are needed:
Write the Changes Back
Dana also needs to add expenses and keep them, so the tracker has to write as well as read. To save, use the recipe from the first section with the converted records. At the end of tracker.js, add a new grocery run and write the whole list back:
expenses.push({
date: new Date("2026-10-14"), category: "groceries",
amount: 52, note: "weekly shop",
});
writeFileSync(
"expenses.json",
JSON.stringify(expenses, null, 2),
);
console.log("Saved", expenses.length, "expenses");
Your tracker now loads, converts, totals, adds, and saves:
tracker.js
import { readFileSync, writeFileSync } from "node:fs";
const text = readFileSync("expenses.json", "utf8");
const expenses = JSON.parse(text).map((expense) => ({
...expense,
date: new Date(expense.date),
amount: Number(expense.amount),
}));
const total = expenses.reduce(
(sum, expense) => sum + expense.amount,
0,
);
console.log("Records:", expenses.length);
console.log("Total:", total);
expenses.push({
date: new Date("2026-10-14"), category: "groceries",
amount: 52, note: "weekly shop",
});
writeFileSync(
"expenses.json",
JSON.stringify(expenses, null, 2),
);
console.log("Saved", expenses.length, "expenses");
Run it once:
$ node tracker.js
Records: 4
Total: 219
Saved 5 expenses
Open expenses.json again. The new record is at the end, and Dana’s "38" is now a bare 38, because the program wrote the converted number. The dates are strings again, so the next load converts them once more. That’s the round trip. You convert on the way in, and JSON.stringify() turns values back into text on the way out.
This is a toy tracker, so it adds the same grocery expense every time you run it. If you run it twice, delete the extra record in your editor.
Want to practice predicting what comes back from a file?
Check Your Understanding
Try these before you open the answers:
- If
textholds{"amount": "12", "date": "2026-10-20"}, how do you parse it intorecordwith a numericamountand aDatedate? - Why does
text[0].amountgiveundefinedinstead of an error whentextcomes fromreadFileSync()? - Why does each of your two conversions need to happen after parsing?
1. Parse, then replace the two fields:
const parsed = JSON.parse(text);
const record = {
...parsed,
date: new Date(parsed.date),
amount: Number(parsed.amount),
};
2. text is a string, so text[0] is its first character, "[". A string has no amount property, and reading a missing property gives undefined without an error.
3. Before parsing, there’s only one string, with no amount or date field to convert. JSON.parse() is what produces the fields, and with them the quoted "38" and the date strings. Then Number() turns a quoted amount into a number, so totals add instead of joining text. new Date() turns each date string back into a Date, because JSON has no date type.
Dana’s tracker now loads the records from expenses.json and fixes their types before saving them back. Next, in Exercise: Convert Expenses To and From JSON, you’ll prepare Dana’s expenses for storage and turn saved text back into records she can total.
You write and run your code in the browser, and selecting Run Tests gives automated feedback on what works and what doesn’t. Run them early and often, read error messages for clues, and use Full screen for more room.