Working with files in Node.js
Course contents (16 lessons)
- Modern syntax
- Destructuring, spread and rest
- ES modules: import and export
- Objects, this and errors
- Classes and prototypes
- Understanding this in JavaScript
- Error handling: try, catch and custom errors
- Asynchronous JavaScript
- The event loop: how JavaScript handles waiting
- From callbacks to promises to async/await
- Fetch and REST APIs
- Working in the browser
- Local storage and session storage
- Debugging with browser DevTools
- Performance basics: debounce and throttle
- Node.js essentials
- Node.js and npm basics
- Working with files in Node.js
- A tiny HTTP server with Node.js
- Testing and the final project
- Testing basics with the Node.js test runner
- Final project: a post explorer with modules and fetch
Files are where Node shines
Browsers cannot read your hard drive, but Node can. Use it for reading config files, processing logs, generating reports and storing small data. Node's fs module has callback, synchronous and promise versions of every function. For new code I use the promise version, node:fs/promises, with await.
Reading and writing text files
import { mkdtemp, writeFile, readFile, appendFile, readdir, stat, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
// work in a temporary folder so we leave nothing behind
const dir = await mkdtemp(path.join(tmpdir(), "demo-"));
const file = path.join(dir, "notes.txt");
await writeFile(file, "First line\n", "utf8");
await appendFile(file, "Second line\n", "utf8");
const text = await readFile(file, "utf8");
console.log(text);
const lines = text.trim().split("\n");
console.log("Line count:", lines.length);
const info = await stat(file);
console.log("Size in bytes:", info.size);
console.log("Files in folder:", await readdir(dir));
await rm(dir, { recursive: true, force: true });
Here is what it does. mkdtemp makes a new unique folder in the system temp directory. writeFile creates a file, or replaces it if it exists. appendFile adds to the end. readFile with "utf8" gives you text. Without the encoding, you get a Buffer of raw bytes. stat gives size and dates, readdir lists a folder, and rm deletes. The top-level await works because this is an ES module.
The very important thing is that writeFile overwrites without warning. If you only want to add to a file, use appendFile, or use the flag: "wx" option, which fails if the file already exists.
Building paths correctly
Never join paths with + or by typing slashes. Windows uses backslashes, Linux uses forward slashes. The path module handles it:
import path from "node:path";
console.log(path.join("data", "users", "list.json")); // data/users/list.json (data\users\list.json on Windows)
console.log(path.basename("/a/b/report.pdf")); // report.pdf
console.log(path.extname("/a/b/report.pdf")); // .pdf
console.log(path.dirname("/a/b/report.pdf")); // /a/b
console.log(path.resolve("notes.txt")); // absolute path from the current folder
Where is my file?
Relative paths such as "notes.txt" are relative to the folder where you ran node, not the folder where the script lives. That causes the "file not found" errors that confuse beginners. To build a path relative to the script in ES modules, use import.meta.dirname (Node 20.11 and later):
const dataFile = path.join(import.meta.dirname, "data.json");
JSON files as a tiny database
For small tools, a JSON file is enough to store data. Reading and writing is two functions:
import { readFile, writeFile } from "node:fs/promises";
async function loadJson(file, fallback) {
try {
return JSON.parse(await readFile(file, "utf8"));
} catch (error) {
if (error.code === "ENOENT") return fallback; // file does not exist yet
throw error;
}
}
async function saveJson(file, data) {
await writeFile(file, JSON.stringify(data, null, 2), "utf8");
}
const todos = await loadJson("todos.json", []);
todos.push({ id: Date.now(), text: "Learn fs", done: false });
await saveJson("todos.json", todos);
JSON.stringify(data, null, 2) indents the file with two spaces so it is readable by humans. The error code ENOENT means "no such file or directory". Checking the code lets us treat a missing file as normal and still crash on other, real problems such as bad permissions.
This approach has limits. If two processes write at the same time, one can overwrite the other, and a crash in the middle of a write can leave a broken file. For anything serious, use a real database.
Reading big files with streams
readFile loads the whole file into memory. For a 2 GB log file, that is a problem. Streams read in chunks. The simplest way to process a big text file by line is:
import { createReadStream } from "node:fs";
import readline from "node:readline";
const rl = readline.createInterface({
input: createReadStream("big.log"),
crlfDelay: Infinity,
});
let errors = 0;
for await (const line of rl) {
if (line.includes("ERROR")) errors++;
}
console.log("Errors:", errors);
Memory use stays small, whatever the file size.
Errors you will see
| Code | Meaning |
|---|---|
ENOENT | File or folder does not exist |
EACCES | No permission |
EEXIST | Already exists |
EISDIR | You tried to read a folder as a file |
Always handle the case where a file might not exist.
Common mistakes
- Using relative paths and running from another folder. Build the path from
import.meta.dirname. - **Forgetting
"utf8".** You get a Buffer printed as bytes. - **Overwriting by accident with
writeFile.** UseappendFileto add. - Using the sync versions in a server.
readFileSyncblocks the event loop for every user. It is fine in a startup script or a small CLI tool. - **Forgetting
await.** The file operation runs but your code races ahead. - Building paths with string concatenation. Use
path.join.
Try it yourself
- Write a script that creates a file with five lines of text and then reads it and prints the longest line.
- Write
countWords(file)that returns the number of words in a text file. - List all
.jsfiles in a folder withreaddirandpath.extname. - Make a small notes tool:
node notes.js add "buy milk"appends tonotes.json, andnode notes.js listprints every note.
import { mkdtemp, writeFile, readFile, appendFile, readdir, stat, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
// work in a temporary folder so we leave nothing behind
const dir = await mkdtemp(path.join(tmpdir(), "demo-"));
const file = path.join(dir, "notes.txt");
await writeFile(file, "First line\n", "utf8");
await appendFile(file, "Second line\n", "utf8");
const text = await readFile(file, "utf8");
console.log(text);
const lines = text.trim().split("\n");
console.log("Line count:", lines.length);
const info = await stat(file);
console.log("Size in bytes:", info.size);
console.log("Files in folder:", await readdir(dir));
await rm(dir, { recursive: true, force: true });
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account