Node comes with a bunch of built-in modules. You import them using a name that starts with node:. The one you'll use most is node:fs (short for "file system"), which lets you read and write files. Its promise-based version lives at node:fs/promises, so you can use it with async/await from Freshman year.
Let's write a little program that saves a note to a file and reads it back. Make a folder called node-practice, and in it, create package.json containing just this:
{
"type": "module"
}
Then create notes.js:
import { readFile, writeFile } from "node:fs/promises";
const note = "Remember to buy plantain! 🍌";
await writeFile("note.txt", note);
console.log("✍️ Note saved.");
const contents = await readFile("note.txt", "utf8");
console.log(`📖 The note says: ${contents}`);
Output
✍️ Note saved. 📖 The note says: Remember to buy plantain! 🍌
Run it with node notes.js:
Check your folder: there's a new file called note.txt! Your JavaScript just created a real file on your computer.
(Notice that we used await at the top level of the file, outside of any function. That's allowed in ES modules. It isn't allowed in regular scripts, which is why we always wrapped our awaits inside async functions in Freshman year.)
The "utf8" tells readFile to give us text. Without it, you'd get raw bytes. Saving and loading JSON works just like localStorage did in Grade 12:
const data = { name: "Mia", highScore: 4200 };
await writeFile("save.json", JSON.stringify(data, null, 2));
const loaded = JSON.parse(await readFile("save.json", "utf8"));
console.log(loaded.highScore); // 4200