T8 Node.js · Lesson 4
Files
A program forgets everything when it ends, unless it writes it down. Node's fs module reads and writes the files on a disk: text, bytes and JSON, folders and their contents. Learn the three ways to ask for a file, read Node's errors by their codes, and build paths that work from any folder.
- read a text file with fs.readFileSync, and write and add to one with writeFileSync and appendFileSync
- say what a byte and a Buffer are, and why a file read without an encoding gives a Buffer
- keep a program's data in a JSON file, and read it back
- make, list, look at, move and remove folders and files
- read Node's errors by their codes, such as ENOENT and EEXIST, and handle the ones you expect
- ask for a file in three ways: synchronous, with a callback, and with a promise and await
- build paths with the path module and __dirname, so that a program finds its files from any folder
The back cover
A program forgets everything when it ends, unless it writes it down. Node's fs module reads and writes the files on a disk, so that a program's work can outlive the program.
These pages show how to read and write a whole file, and the bytes behind its text. They show how to keep data in JSON files, and how to make, list, move and remove folders. They show the errors that file work brings, the three forms every fs function comes in, and how to build paths that work from anywhere.
Before you start
The story: The engine forgets
At dawn the great engine is stopped for oiling, as it is every week. When it turns again, the whole night is gone: the gauge readings, the count of runners, the list of doors to open at six. The engine kept all of it in its head, and its head was empty.
The night clerk stares at the board. Eight hours of readings, and not one written down.
Foreman Tappet takes a ledger from the shelf by the wall and drops it on the bench. "What the engine holds in its head lasts only while it turns," she says. "What matters goes into the ledgers. Teach it to read and write its own."
Every program so far has kept its data in variables. Variables live in the computer's memory, and memory is wiped when the program ends. Run the program again, and it starts from nothing.
A file is data kept on a disk, with a name. It stays after the program ends, after the computer is switched off, and until someone removes it. This lesson teaches Node to read and write files, so that a program can remember.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| One engine, one job at a time. | node app.js | Reading a file can make the engine wait. |
| Callbacks. | setTimeout(() => {}, 0) | Node calls one when a file is ready. |
| Promises and await. | await promise | One of the three ways to ask for a file. |
| Built-in modules. | require("fs") | fs and path come with Node. |
| try and catch. | try { } catch (e) { } | Catching a file that is not there. |
| Splitting a string. | "a b".split(" ") | Turning a file into lines and words. |
| JSON. | JSON.stringify({ pump: 7 }) | Keeping data in a file. |
| Exit codes. | echo $? | A crash ends with the code 1. |
| Relative paths. | cd .. | Where Node looks for a file. |
| cat and ls. | cat log.txt | Checking what a program wrote. |
| The module's own folder. | __dirname | Finding a file from any folder. |
By the end of this lesson you will be able to:
- read a text file with fs.readFileSync, and write and add to one with writeFileSync and appendFileSync;
- say what a byte and a Buffer are, and why a file read without an encoding gives a Buffer;
- keep a program's data in a JSON file, and read it back;
- make, list, look at, move and remove folders and files;
- read Node's errors by their codes, such as ENOENT and EEXIST, and handle the ones you expect;
- ask for a file in three ways: synchronous, with a callback, and with a promise and await;
- build paths with the path module and __dirname, so that a program finds its files from any folder.
How to follow this lesson
Every block runs on the page, in a small Node that keeps its files in the page's memory. A block starts in the shop's folder, with the files that its label names. After node, lines such as cat and ls show what the program left behind. Each block has also been run in real Node 22, and both print exactly what you see.
In one line
This lesson is about files: reading and writing text, bytes, JSON, folders, Node's errors, the three ways to ask, and paths.
Reading and writing a file
At a glance
A file is the simplest memory a program has. Writing to it saves something for later; reading it brings that back.
fs.readFileSync(name, "utf8") reads a whole file and gives back its text. fs.writeFileSync replaces everything in a file with new content, making the file if it is not there. fs.appendFileSync adds to the end instead. None of them adds a newline for you: every line break in a file is one you wrote yourself. The name can be a path, such as logs/today.txt.
Take a guess: Can writeFileSync refuse to write over a file that already exists?
Node keeps everything it can do with files in a built-in module called fs, short for file system. The file system is the part of the computer that keeps files in folders and finds them by their names.
A program loads fs once, at the top, and then calls its functions.
Reading a whole file
The night's readings are in a file called readings.txt, one gauge on each line. This program reads the whole file into a string and prints it:
app.js
const fs = require("fs");
const text = fs.readFileSync("readings.txt", "utf8");
console.log(text);
Terminal: node app.js
boiler 95
pump 40
press 70
The function readFileSync takes the file's name and gives back its whole content. The name is looked for in the folder where you ran node, here the shop's folder.
The second argument, "utf8", is the file's encoding: the rule that turns what is stored on the disk into characters. UTF-8 is the encoding of almost every text file today. The next section shows what you get without it.
Look at the empty line at the end of the output. A text file usually ends with a newline character, and console.log adds one more of its own. JSON.stringify shows the hidden characters, each newline written as \n:
app.js
const fs = require("fs");
const text = fs.readFileSync("readings.txt", "utf8");
console.log(JSON.stringify(text));
Terminal: node app.js
"boiler 95\npump 40\npress 70\n"
Sync at the end of the name means synchronous. The engine waits until the whole file has been read, and only then goes on to the next line.
That is the plainest way, and the right one for a small file at the start of a program. A later section, Three ways to ask, shows the other two ways and when each one is better.
Writing a file
The function writeFileSync takes a name and the text to put in it. If the file does not exist, it is made. If it exists, everything in it is replaced. The terminal's cat then shows what the program left behind:
app.js
const fs = require("fs");
fs.writeFileSync("log.txt", "engine started\n");
console.log("written");
Terminal: node app.js
cat log.txt
written
engine started
A second write does not add to the first. It starts the file again:
app.js
const fs = require("fs");
fs.writeFileSync("log.txt", "first\n");
fs.writeFileSync("log.txt", "second\n");
Terminal: node app.js
cat log.txt
second
Adding to a file
To add text to the end of a file, keeping what is already there, use appendFileSync. It makes the file too, if it is missing. A log is the usual case: each event adds one line.
app.js
const fs = require("fs");
fs.writeFileSync("log.txt", "engine started\n");
fs.appendFileSync("log.txt", "boiler hot\n");
fs.appendFileSync("log.txt", "pump low\n");
Terminal: node app.js
cat log.txt
engine started
boiler hot
pump low
Each piece of text ends with \n, and you write it yourself. Neither function adds a newline of its own. Without them, the three lines would run together into one.
| Function | What it does | If the file is missing |
|---|---|---|
readFileSync(name, "utf8") | gives back the whole file as a string | an error (a later section reads it) |
writeFileSync(name, text) | replaces everything in the file with text | makes it |
appendFileSync(name, text) | adds text at the end of the file | makes it |
Write, then look
After a program writes a file, look at the file with cat in the terminal. It shows exactly what the program left, newlines and all, and a missing newline shows at once.
From text to lines
A file read as text is one long string. To work with it line by line, split it at each newline. Call trim() first: it removes the newline at the very end, so that the last line is not an empty string.
app.js
const fs = require("fs");
const lines = fs.readFileSync("readings.txt", "utf8").trim().split("\n");
console.log(lines);
console.log(lines.length, "readings");
Terminal: node app.js
[ 'boiler 95', 'pump 40', 'press 70' ]
3 readings
Then each line can be split again, at its space, into a name and a number. That is all a program needs to work with the night's readings.
Worked example 1
The night clerk wants the names of the gauges that read more than 60, written to a file called hot.txt, one name on each line.
What we have: readings.txt, three lines, each with a gauge's name and its reading
What we need: hot.txt, holding the names of the gauges above 60
The plan: read the file and split it into lines; split each line into its name and its number; keep the names above 60; write them, one on each line
app.js
const fs = require("fs");
const lines = fs.readFileSync("readings.txt", "utf8").trim().split("\n");
const hot = [];
for (const line of lines) {
const [name, value] = line.split(" ");
if (Number(value) > 60) hot.push(name);
}
fs.writeFileSync("hot.txt", hot.join("\n") + "\n");
console.log(hot.length, "hot gauges");
Terminal: node app.js
cat hot.txt
2 hot gauges
boiler
press
- The pattern
const [name, value] = line.split(" ")takes the two parts of each line into two names at once. Number(value)turns the text 95 into the number 95, so the comparison is between numbers. Two strings, such as "95" and "100", are compared character by character, and "95" would come out larger.- The names are joined with newlines, and one more newline ends the file, as a text file should.
hot.txt holds boiler and press, one on each line.
Check: Find the readings above 60 by eye: 95 and 70, two of the three. The program says 2, and cat shows the same two names.
Another way: the same in a chain: lines.map((l) => l.split(" ")).filter(([, v]) => Number(v) > 60).map(([n]) => n) gives the same two names.
A path that fails: writing hot.join("\n") with no newline at the end. The file still works, but its last line is unfinished, and in a real terminal cat leaves the prompt on the same line as press.
When you are stuck: A file reads wrongly
Numbers in angle brackets, such as <Buffer 62 6f 69>, mean that "utf8" was left out. Add it as the second argument.
To work with lines, split at \n, and call trim() first, or the last line will be an empty string.
To see exactly what a string holds, print JSON.stringify(text). Every newline shows as \n.
If old text is gone, a writeFileSync replaced it. Use appendFileSync to add.
Your turn
Which function adds a line to the end of a file, without removing what is there?Tap to reveal
- writeFileSync replaces everything in the file.
appendFileSync.
What does the second argument, "utf8", of readFileSync choose?Tap to reveal
- The disk stores something that is not yet characters.
The encoding: how the stored data becomes characters.
node -p 'require("fs").readFileSync("readings.txt", "utf8").split("\n").length'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
4
- The file has three lines, each ending with a newline.
- Splitting at three newlines gives four pieces.
- The last piece is the empty string after the final newline.
It prints 4: the three lines and an empty string. With trim() first, it would be 3.
Did you know?
A write that will not overwrite
A write can be told never to replace an existing file. The Node manual lists file system flags, given as the flag option: w opens a file for writing and empties it if it exists, while wx is like w but fails if the path exists. So fs.writeFileSync(name, text, { flag: "wx" }) makes a new file, or throws an error instead of wiping out an old one.
Why it fits here: It answers this topic's question: the flag wx makes writeFileSync fail rather than replace an existing file.
Two kinds of line ending
A newline is not the same everywhere. The Node manual says os.EOL holds the operating system's own end-of-line marker: a single \n on POSIX systems such as Linux, and the pair \r\n on Windows. A file written on one system can therefore show odd line endings on the other, and os.EOL lets a program write the local kind.
Why it fits here: It adds to this topic's newlines: Linux ends a line with \n and Windows with \r\n, and os.EOL holds the local one.
Source: Node.js manual: OS
In one line
fs.readFileSync(name, "utf8") reads a whole file as text; writeFileSync replaces a file's content; appendFileSync adds to its end; you write every newline yourself.
Text and bytes: Buffers
At a glance
Underneath its text, a file holds only bytes: numbers from 0 to 255. An encoding such as UTF-8 turns those bytes into characters.
When readFileSync is given an encoding, it gives back text. Without one, it gives back a Buffer, a row of raw bytes. A Buffer's length counts bytes, not characters, and its toString() turns the bytes into text again. Node prints a Buffer with each byte as two hexadecimal digits. Pictures and sounds are read as bytes, since they are not text at all.
Take a guess: Can a new Buffer hold old, leftover data from memory?
Underneath, a file holds no characters at all. It holds bytes: small whole numbers from 0 to 255, one after another.
An encoding is the rule that turns bytes into characters. In UTF-8, the letter b is the byte 98, the letter o is 111, and a newline is 10.
Leave the encoding out, and readFileSync gives you the bytes themselves, in a Buffer. A Buffer is Node's object for a row of bytes.
app.js
const fs = require("fs");
const data = fs.readFileSync("readings.txt");
console.log(data);
console.log(data.length, "bytes");
Terminal: node app.js
<Buffer 62 6f 69 6c 65 72 20 39 35 0a 70 75 6d 70 20 34 30 0a 70 72 65 73 73 20 37 30 0a>
27 bytes
Node prints each byte as two hexadecimal digits. Hexadecimal, or hex, counts in sixteens, with the digits 0 to 9 and then a to f.
So 62 in hex is 6 × 16 + 2, which is 98: the letter b. And 0a is 10, the newline at the end of each line. The file has 27 bytes: 10 for the first line, 8 for the second and 9 for the third.
A Buffer works like an array of numbers. data[0] is the first byte, and data.length counts the bytes. Its toString() turns the bytes back into text, by UTF-8 unless you name another encoding:
app.js
const fs = require("fs");
const data = fs.readFileSync("readings.txt");
console.log(data[0], data[1], data[9]);
console.log(data.toString().split("\n")[0]);
Terminal: node app.js
98 111 10
boiler 95
One character, several bytes
For the letters of English, one character takes one byte. Many characters need more. The rupee sign, ₹, takes three bytes in UTF-8.
So a string's length, which counts characters, and a Buffer's length, which counts bytes, can differ:
app.js
const price = "₹40 pump";
const bytes = Buffer.from(price);
console.log(price.length, "characters");
console.log(bytes.length, "bytes");
console.log(bytes);
Terminal: node app.js
8 characters
10 bytes
<Buffer e2 82 b9 34 30 20 70 75 6d 70>
Buffer.from(text) turns text into bytes, by UTF-8. The rupee sign became e2 82 b9, three bytes; the other seven characters took one byte each.
Buffer.byteLength(text) counts the bytes without making a Buffer. Buffer is a global in Node, like console, so no require is needed.
Why bytes matter
Most files are not text at all: a photo, a sound, a zip file. Their bytes follow rules of their own, and reading them as UTF-8 would spoil them.
A program that copies such a file reads a Buffer and writes the same Buffer back, without ever turning it into text. Limits are often counted in bytes too: a field of 16 bytes holds 16 letters, but only five rupee signs.
Bytes written as text: hex and base64
Sometimes bytes must travel inside text, such as a web address or a JSON file. Two encodings write any bytes with plain characters.
Hex uses two characters for each byte. Base64 is shorter: four characters for every three bytes, with = signs to fill the end.
app.js
const b = Buffer.from("pump");
console.log(b.toString("hex"));
console.log(b.toString("base64"));
console.log(Buffer.from("cHVtcA==", "base64").toString());
Terminal: node app.js
70756d70
cHVtcA==
pump
| Expression | Gives |
|---|---|
fs.readFileSync(name) | a Buffer: the file's bytes |
fs.readFileSync(name, "utf8") | a string: the file's text |
Buffer.from(text) | the text's bytes, in UTF-8 |
buf.toString() | the bytes as text, by UTF-8 |
buf.length | the number of bytes |
Buffer.byteLength(text) | how many bytes the text takes |
buf.toString("hex"), buf.toString("base64") | the bytes, written with plain characters |
Worked example 2
The ticket printer at the hall's gate prints at most 12 bytes on a line. Which of these labels fit: pump 40, ₹40 pump, boiler ₹95 and ₹₹₹ press?
What we have: four labels, and a limit of 12 bytes
What we need: for each label, whether its bytes fit
The plan: count each label's characters and its bytes, and compare the bytes with 12
app.js
const labels = ["pump 40", "₹40 pump", "boiler ₹95", "₹₹₹ press"];
for (const label of labels) {
const bytes = Buffer.byteLength(label);
console.log(label, label.length, bytes, bytes <= 12 ? "fits" : "too long");
}
Terminal: node app.js
pump 40 7 7 fits
₹40 pump 8 10 fits
boiler ₹95 10 12 fits
₹₹₹ press 9 15 too long
- The second number is the label's length in characters, the third its length in bytes.
- Each rupee sign adds two bytes more than it adds characters. ₹₹₹ press has 9 characters, but 15 bytes.
Three labels fit. ₹₹₹ press is too long: 9 characters, but 15 bytes.
Check: Count by hand: each ₹ is 3 bytes and every other character 1. For ₹₹₹ press, 3 × 3 + 6 is 15.
A path that fails: testing label.length <= 12, which counts characters. Every label passes, and the printer cuts ₹₹₹ press short.
When you are stuck: Bytes and characters do not match
A string's length counts characters; a Buffer's length counts bytes. Count bytes with Buffer.byteLength(text).
A Buffer printed as <Buffer ...> is not broken. Call toString() to see its text.
To look at one byte, use data[0]. It is a number from 0 to 255, and the hex in the printout is the same number in sixteens.
Your turn
How many bytes does a newline take in UTF-8?Tap to reveal
- It shows as 0a in a Buffer's printout.
One byte: 0a in hex, which is 10.
What does fs.readFileSync("readings.txt") give, with no encoding?Tap to reveal
- The encoding is what turns bytes into characters.
A Buffer holding the file's bytes.
node -p 'Buffer.byteLength("₹") + "₹".length'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
4
- Buffer.byteLength counts bytes: the rupee sign takes 3.
- A string's length counts characters: 1.
- 3 + 1 is 4.
It prints 4.
Did you know?
A Buffer is a Uint8Array
Buffer is not a stranger to JavaScript. The Node manual says the Buffer class is a subclass of JavaScript's own Uint8Array, a typed array of 8-bit numbers, extended with extra methods. Node's functions accept a plain Uint8Array wherever they accept a Buffer. So what you learn about typed arrays in the browser also works on the bytes of a file.
Why it fits here: It places this topic's Buffer in the language: it is JavaScript's Uint8Array with extra methods.
Source: Node.js manual: Buffer
allocUnsafe can show old memory
Buffer.allocUnsafe lives up to its name. The Node manual says the memory behind a Buffer made this way is not initialized, so its contents are unknown and may contain sensitive data left over in memory. It points to Buffer.alloc instead, which fills a new Buffer with zeroes. allocUnsafe is faster, and safe only when every byte is written before it is read.
Why it fits here: It answers this topic's question: Buffer.allocUnsafe may hold leftover data, while Buffer.alloc starts with zeroes.
Source: Node.js manual: Buffer
In one line
A file holds bytes, and an encoding such as UTF-8 turns them into characters. Without an encoding, readFileSync gives a Buffer: its length counts bytes, and toString() makes text again.
Data in files: JSON
At a glance
Data in a program, such as an object of settings, vanishes when the program ends. JSON turns it into text that a file can keep.
To save, JSON.stringify turns the data into text and writeFileSync writes it. To load, readFileSync reads the text and JSON.parse turns it back into data. To change one value in a JSON file, read the whole file, change the data, and write it all back: a JSON file cannot be edited in place. JSON files are text, so people can read them too.
Take a guess: What happens to a JSON file if the program stops halfway through writing it?
Lines of text work for simple data. A program's real data is usually objects and arrays: a pump with its pressure and whether it is open, or a list of orders.
JSON, which you met in the JavaScript track, writes such data as text, so it fits in a file. A file of JSON usually has a name that ends in .json.
Saving and loading
Saving takes two steps. JSON.stringify turns the data into text, and writeFileSync writes the text.
Loading is the same two steps backwards: readFileSync reads the text, and JSON.parse turns it back into data.
app.js
const fs = require("fs");
const pump = { name: "pump 2", pressure: 3.5, open: true };
fs.writeFileSync("pump.json", JSON.stringify(pump, null, 2) + "\n");
const back = JSON.parse(fs.readFileSync("pump.json", "utf8"));
console.log(back.pressure + 1, back.open);
Terminal: node app.js
cat pump.json
4.5 true
{
"name": "pump 2",
"pressure": 3.5,
"open": true
}
The two extra arguments of JSON.stringify, null and 2, make the file easy to read: one field on each line, indented by two spaces. Without them, the whole object would be one long line, which a program reads just as well and a person less well.
What comes back is a new object with the same fields and values. The pressure is a number again, so back.pressure + 1 is 4.5.
A program that remembers
Now the engine can remember between runs. This program counts how many times it has been run. It loads its state if the file is there, changes it, and saves it again:
app.js
const fs = require("fs");
let state = { runs: 0 };
if (fs.existsSync("state.json")) {
state = JSON.parse(fs.readFileSync("state.json", "utf8"));
}
state.runs += 1;
fs.writeFileSync("state.json", JSON.stringify(state) + "\n");
console.log("run number", state.runs);
Terminal: node app.js
node app.js
node app.js
cat state.json
run number 1
run number 2
run number 3
{"runs":3}
fs.existsSync(name) answers true or false: whether a file or folder of that name exists. The first run finds no state.json, so it starts from zero runs. Each later run starts from what the last one saved.
This pattern, read, change, write, is how most small programs keep their data.
What JSON keeps, and what it drops
JSON knows numbers, strings, true, false, null, arrays and objects. Anything else changes on the way, or is left out:
app.js
const text = JSON.stringify({ pump: 7, note: undefined, at: new Date(0) });
console.log(text);
console.log(typeof JSON.parse(text).at);
Terminal: node app.js
{"pump":7,"at":"1970-01-01T00:00:00.000Z"}
string
| In the program | In the JSON text | Read back as |
|---|---|---|
3.5, "pump" | 3.5, "pump" | the same number and string |
true, false, null | the same words | the same values |
[1, 2], { a: 1 } | [1,2], {"a":1} | a new array, a new object |
| a Date | its time as a string | a string, not a Date |
undefined, a function | left out of the object | missing |
require reads JSON too, but only once
Lesson 02 showed that require can load a JSON file. It loads it once: the module cache keeps the first answer, even after the file has changed. For data that changes, read the file with fs:
app.js
const fs = require("fs");
fs.writeFileSync("pump.json", '{ "pump": 7 }\n');
console.log(require("./pump.json").pump);
fs.writeFileSync("pump.json", '{ "pump": 8 }\n');
console.log(require("./pump.json").pump);
console.log(JSON.parse(fs.readFileSync("pump.json", "utf8")).pump);
Terminal: node app.js
7
7
8
Use require for a JSON file that stays the same while the program runs, such as settings that come with it. Use readFileSync and JSON.parse for data.
When the text is not JSON
JSON.parse throws a SyntaxError when the text is not valid JSON. A common cause is a file written by hand, with its names not in double quotes:
app.js
const fs = require("fs");
const text = fs.readFileSync("settings.json", "utf8");
try {
JSON.parse(text);
} catch (e) {
console.log(e.name, "in settings.json:", text.trim());
}
Terminal: node app.js
SyntaxError in settings.json: { pump: 7 }
In JSON, every name is in double quotes: { "pump": 7 }. JSON also allows no comma after the last item, and no comments.
Worked example 3
The pump-house keeps its orders in orders.json, an array. Add a new order, open gate 6 at 06:00, and keep the old ones.
What we have: orders.json, an array holding one order
What we need: the same file, with the new order added after the old one
The plan: load the array, push the new order onto it, and save the whole array again
app.js
const fs = require("fs");
const orders = JSON.parse(fs.readFileSync("orders.json", "utf8"));
orders.push({ gate: 6, action: "open", at: "06:00" });
fs.writeFileSync("orders.json", JSON.stringify(orders, null, 2) + "\n");
console.log(orders.length, "orders");
Terminal: node app.js
cat orders.json
2 orders
[
{
"gate": 4,
"action": "close"
},
{
"gate": 6,
"action": "open",
"at": "06:00"
}
]
- JSON.parse gives a real array, so push works on it as on any array.
- The whole array is written back. A JSON file cannot grow by appending: it is one value, from its first bracket to its last.
orders.json holds two orders, the old one first.
Check: cat shows both orders inside one pair of square brackets, so the file is still one valid JSON value.
A path that fails: appending the new order with fs.appendFileSync. The file then holds an array followed by an object, which is not valid JSON, and the next JSON.parse throws a SyntaxError.
When you are stuck: JSON.parse throws a SyntaxError
Print the text before parsing it. console.log(JSON.stringify(text)) shows every character, the hidden ones too.
Check the rules: names in double quotes, no comma after the last item, no comments.
An empty file is not valid JSON either. Did a program write the file empty?
Your turn
Which line saves the object data to data.json?Tap to reveal
- One call turns data into text, the other writes the text.
fs.writeFileSync("data.json", JSON.stringify(data)).
Why does require give the old value after a JSON file has changed?Tap to reveal
- Lesson 02: a module is loaded once.
The module cache keeps the first answer. Read data with fs and JSON.parse.
node -p 'JSON.stringify({ a: 1, b: undefined })'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
{"a":1}
- JSON has no undefined.
- A field whose value is undefined is left out.
It prints {"a":1}.
Did you know?
Indents stop at 10
The number in JSON.stringify(data, null, 2) has a ceiling. MDN explains that this third argument, when it is a number, gives the number of spaces to indent with, clamped to 10: any number above 10 is treated as 10. A value below 1 means no indentation at all, and the whole text comes out on one line.
Why it fits here: It sharpens this topic's JSON.stringify: its indent is at most 10 spaces, and below 1 there is none.
Sources: MDN: JSON.stringify(); ECMAScript Language Specification: JSON.stringify
Write to a copy, then rename
A program that stops halfway through writeFileSync can leave a broken JSON file. A safer habit writes the new text to a temporary file first, then renames it over the old one. The Linux manual for rename says that if the new name already exists, it is replaced atomically: no other program will ever find the file missing. Readers see the old file or the new one, never half of one.
Why it fits here: It answers this topic's question: writing to a temporary file and renaming it means no reader ever sees a half-written JSON file.
Source: Linux man-pages: rename(2)
In one line
JSON.stringify and writeFileSync save data; readFileSync and JSON.parse load it back. Change a JSON file by reading it, changing the data and writing it whole.
Folders: make, list, look, move, remove
At a glance
Files live in folders, and a program often has to make, read and tidy those folders, just as you did in the shell.
Node's fs has a function for each shell command you know: mkdirSync for mkdir, readdirSync for ls, statSync for stat, renameSync for mv, copyFileSync for cp and unlinkSync and rmSync for rm. The option recursive: true reaches the folders below, as -p and -r do in the shell. The same care applies: rmSync has no bin either.
Take a guess: Can Node copy a whole folder, everything inside it included, in one call?
Files live in folders, and a program often needs to make folders, see what is in them, and tidy them. Each of these fs functions does what a shell command from the Linux track does:
| In the shell | In Node | What it does |
|---|---|---|
mkdir logs | fs.mkdirSync("logs") | makes a folder |
mkdir -p a/b/c | fs.mkdirSync("a/b/c", { recursive: true }) | makes every missing folder on the way |
ls | fs.readdirSync(".") | lists the names in a folder |
[ -e x ] | fs.existsSync("x") | true if it exists |
stat x | fs.statSync("x") | facts about it: size, kind, times |
mv a b | fs.renameSync("a", "b") | moves or renames |
cp a b | fs.copyFileSync("a", "b") | copies a file |
rm a | fs.unlinkSync("a") | removes a file |
rmdir d | fs.rmdirSync("d") | removes an empty folder |
rm -r d | fs.rmSync("d", { recursive: true }) | removes a folder and everything in it |
Making folders
The function mkdirSync makes one folder. With { recursive: true }, it makes every missing folder on the way, as mkdir -p does:
app.js
const fs = require("fs");
fs.mkdirSync("logs/2026/11", { recursive: true });
fs.writeFileSync("logs/2026/11/09.txt", "boiler 95\n");
console.log(fs.readdirSync("logs"));
console.log(fs.readdirSync("logs/2026/11"));
Terminal: node app.js
ls -R logs
[ '2026' ]
[ '09.txt' ]
logs:
2026
logs/2026:
11
logs/2026/11:
09.txt
Without recursive, mkdirSync fails when the folder is already there, or when the folder above it is missing. With recursive, it makes what is missing and is content when everything is already there.
What is in a folder
The function readdirSync gives the names in a folder as an array of strings, files and folders alike. On Linux, the names come sorted. The names are only names: to use one, join it to the folder's path.
To tell files from folders, ask for { withFileTypes: true }. Each item is then an object with a name and the methods isFile() and isDirectory(). This program marks folders with a slash, as ls -F does:
app.js
const fs = require("fs");
for (const entry of fs.readdirSync(".", { withFileTypes: true })) {
console.log(entry.isDirectory() ? entry.name + "/" : entry.name);
}
Terminal: node app.js
app.js
logs/
notes.txt
readings.txt
tools/
Facts about a file: stat
The function statSync gives an object of facts about a file or folder, called its stats: its size in bytes, its times, and methods that say what kind of thing it is.
app.js
const fs = require("fs");
const s = fs.statSync("readings.txt");
console.log(s.size, "bytes");
console.log(s.isFile(), s.isDirectory());
console.log(fs.statSync("logs").isDirectory());
Terminal: node app.js
27 bytes
true false
true
The stats also hold times, such as s.mtime, the time of the last change. Times differ on every machine, so this lesson never prints them.
Moving, copying and removing
app.js
const fs = require("fs");
fs.mkdirSync("old");
fs.renameSync("readings.txt", "old/readings.txt");
fs.copyFileSync("old/readings.txt", "copy.txt");
fs.unlinkSync("old/readings.txt");
console.log(fs.readdirSync("."), fs.readdirSync("old"));
Terminal: node app.js
[ 'app.js', 'copy.txt', 'old' ] []
renameSync(from, to) gives a file a new path, which may be in another folder: a move and a rename are the same operation. The new path is the file's full new name, folder and all.
copyFileSync(from, to) copies a file, and replaces the copy if one is already there. unlinkSync removes one file. Unlink is the system's old word for removing a file's name from its folder.
Removing a folder
The function rmdirSync removes a folder only when it is empty. rmSync with { recursive: true } removes a folder with everything inside it, like rm -r.
Add force: true, and rmSync says nothing when the path is missing, like rm -f.
app.js
const fs = require("fs");
try {
fs.rmdirSync("logs");
} catch (e) {
console.log(e.code);
}
fs.rmSync("logs", { recursive: true });
console.log(fs.existsSync("logs"));
fs.rmSync("logs", { recursive: true, force: true });
console.log("no error the second time");
Terminal: node app.js
ENOTEMPTY
false
no error the second time
There is no undo
rmSync with recursive removes everything below the path at once, with no bin to fetch it back from. When the path is built from data, print it first, and run the program on a copy.
Worked example 4
Tidy the shop's folder: move every .txt file into a folder called archive, making the folder if it is missing, then list both folders.
What we have: a folder holding app.js, notes.txt, readings.txt, orders.json and a folder called tools
What we need: the two .txt files inside archive, and nothing else moved
The plan: make archive; for each name in the folder, if it ends in .txt and is a file, rename it into archive; list both folders
app.js
const fs = require("fs");
fs.mkdirSync("archive", { recursive: true });
for (const name of fs.readdirSync(".")) {
if (name.endsWith(".txt") && fs.statSync(name).isFile()) {
fs.renameSync(name, "archive/" + name);
}
}
console.log(fs.readdirSync("."));
console.log(fs.readdirSync("archive"));
Terminal: node app.js
[ 'app.js', 'archive', 'orders.json', 'tools' ]
[ 'notes.txt', 'readings.txt' ]
- recursive: true lets the program run a second time without failing on the folder it made the first time.
- statSync(name).isFile() keeps folders out, even a folder whose name ends in .txt.
- The new path is the folder's name, a slash and the file's name: renameSync needs the full new name.
archive holds notes.txt and readings.txt; the shop's folder keeps app.js, orders.json and tools.
Check: Before: two .txt files in the shop's folder. After: none there, and two in archive. Nothing else moved.
Another way: path.join("archive", name) builds the same new path. The section on paths shows why it is the safer way.
A path that fails: renameSync(name, "archive"), as if it were mv. A rename needs the full new name, so Node tries to put the file in the folder's own place, and fails with EISDIR.
When you are stuck: A folder operation fails
EEXIST from mkdirSync: the folder is already there. Add { recursive: true } if that is fine.
ENOTEMPTY from rmdirSync: the folder still holds files. Use rmSync with { recursive: true }, if you are sure.
ENOENT from a name that readdirSync gave you: the name lacks its folder. Join the folder's path and the name.
Your turn
Which call makes logs/2026, and makes logs too if it is missing?Tap to reveal
- mkdir -p in the shell.
fs.mkdirSync("logs/2026", { recursive: true }).
Which call removes the folder old with everything inside it?Tap to reveal
- rm -r in the shell.
- rmdirSync only removes an empty folder.
fs.rmSync("old", { recursive: true }).
mkdir -p a/b
node -p 'require("fs").readdirSync("a")'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[ 'b' ]
- readdirSync lists the names inside a.
- a holds one folder, b.
It prints [ 'b' ]: an array with one name.
Did you know?
cp -r in one call
Copying a whole folder needs no loop of your own. The Node manual describes fs.cpSync, added in Node 16.7.0 and no longer experimental since 22.3.0. It copies the entire directory structure from one place to another, subfolders and files included, and with a folder it behaves like cp dir1/ dir2/ in the shell.
Why it fits here: It answers this topic's question: fs.cpSync copies a folder and everything inside it, like cp -r.
Source: Node.js manual: File system
A folder with a random name
Programs often need a scratch folder that clashes with nothing. The Node manual describes fs.mkdtemp, which creates a unique temporary folder. It adds six random characters behind a prefix you give, so mkdtempSync('/tmp/shop-') might make /tmp/shop-a1b2c3. The manual warns that some systems, notably the BSDs, can add more than six.
Why it fits here: It adds to this topic's mkdirSync: mkdtemp makes a folder with a unique random name for scratch work.
Source: Node.js manual: File system
In one line
mkdirSync, readdirSync, statSync, renameSync, copyFileSync, unlinkSync and rmSync do what mkdir, ls, stat, mv, cp and rm do; recursive: true reaches the folders below.
When it goes wrong: Node's errors
At a glance
File work goes wrong in ordinary ways: a file is missing, a folder already exists, a name points to a folder instead of a file.
Node reports each such failure as a system error. It carries a code such as ENOENT or EEXIST, a number errno, the call that failed in syscall, and the path. Test e.code in a catch block, handle the code you expect, and throw everything else again. A missing file you planned for is fine; a surprise should still stop the program.
Take a guess: What does the name ENOENT stand for?
So far, every file was where the program expected it. Real programs meet missing files, folders where files should be, and files that already exist.
Ask readFileSync for a file that is not there, and nothing catches the error. Node stops the program and prints a crash report:
app.js
const fs = require("fs");
const text = fs.readFileSync("nosuch.txt", "utf8");
console.log(text);
Terminal: node app.js
echo "[$?]"
node:fs:440
return binding.readFileUtf8(path, stringToFlags(options.flag));
^
Error: ENOENT: no such file or directory, open 'nosuch.txt'
at Object.readFileSync (node:fs:440:20)
at Object.<anonymous> (/home/asha/shop/app.js:2:17)
at Module._compile (node:internal/modules/cjs/loader:1781:14)
at Object..js (node:internal/modules/cjs/loader:1913:10)
at Module.load (node:internal/modules/cjs/loader:1505:32)
at Function._load (node:internal/modules/cjs/loader:1309:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:36:49 {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'nosuch.txt'
}
Node.js v22.23.1
[1]
Read it from the top. Node first shows where the error was thrown, inside its own code, node:fs. Then comes the error's message.
Then comes the stack: the chain of calls that led to the error, the newest first. Your own line is the first one with your file's name: app.js, line 2, column 17. The lines below it are Node starting your program.
Last come the error's extra fields, in braces, and Node's version. The program ended with the exit code 1, and console.log on line 3 never ran.
What a system error carries
An error that comes from the operating system, such as a missing file, is called a system error. Besides its message, it carries these fields:
| Field | Example | What it says |
|---|---|---|
code | 'ENOENT' | the kind of error, as a short name |
errno | -2 | the same kind, as a number |
syscall | 'open' | the request that Node made to the system |
path | 'nosuch.txt' | the file or folder it was about |
dest | 'b.txt' | a second path, for a rename or a copy |
The code is the field to test in your programs. The number in errno can differ from one system to another; the code does not.
The names come from Unix and are decades old. The E stands for error, and NOENT for no entry: no such file or folder.
The codes you will meet
This program makes five mistakes on purpose, catches each error, and prints its code and message:
app.js
const fs = require("fs");
const tries = [
() => fs.readFileSync("nosuch.txt"),
() => fs.mkdirSync("logs"),
() => fs.readFileSync("logs"),
() => fs.readdirSync("readings.txt"),
() => fs.rmdirSync("logs"),
];
for (const attempt of tries) {
try {
attempt();
} catch (e) {
console.log(e.code, "|", e.message);
}
}
Terminal: node app.js
ENOENT | ENOENT: no such file or directory, open 'nosuch.txt'
EEXIST | EEXIST: file already exists, mkdir 'logs'
EISDIR | EISDIR: illegal operation on a directory, read
ENOTDIR | ENOTDIR: not a directory, scandir 'readings.txt'
ENOTEMPTY | ENOTEMPTY: directory not empty, rmdir 'logs'
A message has three parts: the code, a few words, and the request with its path. The request is the system's name for the work. For example, scandir is how readdirSync reads a folder.
EISDIR shows no path: the read was made on a folder already opened, and the system reports no name for it.
| Code | The words | It usually means |
|---|---|---|
ENOENT | no such file or directory | the file, or a folder on its path, is missing |
EEXIST | file already exists | mkdirSync of a folder that is there |
EISDIR | illegal operation on a directory | a folder read or written as if it were a file |
ENOTDIR | not a directory | a file used as a folder, as in readings.txt/x |
ENOTEMPTY | directory not empty | rmdirSync of a folder that holds files |
EACCES | permission denied | the file's permissions do not allow it |
Handling the error you expect
A missing file is often no surprise. A program that saves its settings will not find them on its first run. Catch the error, check its code, and handle only the case you expect.
Let every other error go on with throw e, so that a real problem is still seen:
app.js
const fs = require("fs");
function loadSettings() {
try {
return JSON.parse(fs.readFileSync("settings.json", "utf8"));
} catch (e) {
if (e.code === "ENOENT") return { pressure: 3 };
throw e;
}
}
try {
console.log(loadSettings());
} catch (e) {
console.log("not handled:", e.code);
}
Terminal: node app.js
{ pressure: 3 }
A missing settings.json gives the defaults, and the program runs on. If settings.json were a folder, the code would be EISDIR, and loadSettings would pass the error on:
app.js
const fs = require("fs");
function loadSettings() {
try {
return JSON.parse(fs.readFileSync("settings.json", "utf8"));
} catch (e) {
if (e.code === "ENOENT") return { pressure: 3 };
throw e;
}
}
try {
console.log(loadSettings());
} catch (e) {
console.log("not handled:", e.code);
}
Terminal: node app.js
not handled: EISDIR
Try, then handle
Node's documentation advises against checking that a file exists and then reading it. Between the two steps, another program may remove the file. Read it, and handle ENOENT. The counter in the JSON section checked first, which is fine for a small program that alone uses its file.
Worked example 5
The hall's logger adds lines to logs/today.txt. On a new machine, the logs folder does not exist yet. Make the logger create the folder when, and only when, a write fails with ENOENT.
What we have: appendFileSync, which makes a missing file but not a missing folder
What we need: a log function that works on a new machine and still reports any other error
The plan: try the append; on ENOENT, make the folder and append again; throw every other error
app.js
const fs = require("fs");
function log(line) {
try {
fs.appendFileSync("logs/today.txt", line + "\n");
} catch (e) {
if (e.code !== "ENOENT") throw e;
fs.mkdirSync("logs", { recursive: true });
fs.appendFileSync("logs/today.txt", line + "\n");
}
}
log("engine started");
log("boiler hot");
Terminal: node app.js
cat logs/today.txt
engine started
boiler hot
- The first call fails with ENOENT, as logs is missing. The catch makes the folder and writes the line.
- The second call succeeds at once: the folder is there now.
if (e.code !== "ENOENT") throw e;keeps every other error visible, such as EACCES on a folder that the program may not write to.
Both lines are in logs/today.txt, and the folder was made once.
Check: cat shows the two lines in order, and a second run would add two more without making anything new.
Another way: make the folder before the first write with fs.mkdirSync("logs", { recursive: true }). It is content when the folder is there, so it is safe to call every time.
A path that fails: an empty catch (e) { }. Every error is hidden, a missing folder and a typing slip in the path alike, and the log quietly stays empty.
When you are stuck: An error you do not understand
Print e.code and e.path first. They say what kind of error, and about which file.
Compare the path with what ls shows. process.cwd() prints the folder where Node looks for a relative path.
A code that starts with ERR_, such as ERR_INVALID_ARG_TYPE, is not a system error. It means a wrong argument, often undefined where a name or text should be.
Your turn
Which code means that a file or folder is missing?Tap to reveal
- NOENT: no entry.
ENOENT.
A program catches every error from readFileSync and prints only "no settings". What can go wrong?Tap to reveal
- What if settings.json is a folder, or may not be read?
It hides real problems. Check e.code, handle ENOENT, and throw the rest.
node -e 'try { require("fs").mkdirSync(".") } catch (e) { console.log(e.code) }'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
EEXIST
- The folder . is the folder you are in.
- It exists already, and recursive was not given.
It prints EEXIST.
Did you know?
ENOENT, no entity
The odd name ENOENT has a meaning. Node's manual of errors says ENOENT, no such file or directory, is commonly raised by fs operations when part of a path does not exist, and explains it as no entity, file or directory, found by the given path. So E-NO-ENT reads as error, no entity: nothing is there.
Why it fits here: It answers this topic's question: ENOENT reads as error, no entity, meaning nothing exists at that path.
Too many open files
A program can run out of file handles. Node's manual of errors describes EMFILE, too many open files: the limit of file descriptors has been reached, and no more can be opened until one is closed. It says this happens when opening many files at once, especially on macOS with its low limit, and suggests raising it with ulimit -n 2048 in the shell that runs Node.
Why it fits here: It adds a code to this topic's list: EMFILE means too many files are open at once, and ulimit -n raises the limit.
In one line
A system error carries code, errno, syscall and path. Test e.code, such as ENOENT or EEXIST, handle the code you expect, and throw everything else.
Three ways to ask: sync, callback, promise
At a glance
Every file job can be asked for in three ways, depending on whether the program may wait or must keep moving.
The Sync form, such as readFileSync, waits and gives back the result. The callback form, readFile, returns at once and calls a function later with an error and a result. The promise form, from fs/promises, gives back a promise to await. All three do the same work and give the same errors; only the waiting differs. Pick the form that suits the program.
Take a guess: Should a web server use the Sync forms?
Reading a file takes time. On this page the files are in memory, but a real disk, or a disk across a network, can take far longer than many lines of JavaScript.
Lesson 01's rule says that the engine must never stand waiting. So Node offers every fs function in three forms, which wait in three different ways.
The first form: synchronous, wait here
The Sync functions, which this lesson has used so far, stop the engine until the work is done. They are the easiest to read, as each line finishes before the next begins.
But while a Sync call waits, nothing else in the program can run: no timer, no other request. For a short script that is no loss. For a server that answers many people at once, every one of them would wait.
The second form: callbacks, call me when it is done
The function without Sync in its name, fs.readFile, starts the work and returns at once, before the file is read. When the file is ready, Node calls a function that you gave it, the callback, from its event loop:
app.js
const fs = require("fs");
fs.readFile("readings.txt", "utf8", (err, text) => {
if (err) {
console.log("could not read:", err.code);
return;
}
console.log("read", text.length, "characters");
});
console.log("asked for the file");
Terminal: node app.js
asked for the file
read 27 characters
The last line printed first. The call to readFile asked for the file and returned, the program went on to its last line, and the callback ran later, when the file was ready.
The callback's first parameter is the error, and its second the result. This order is called error-first, and every callback of Node's own modules follows it.
The error is null when all went well, and an error object when it did not. Check it before you touch the result:
app.js
const fs = require("fs");
fs.readFile("nosuch.txt", "utf8", (err, text) => {
if (err) {
console.log("could not read:", err.code);
return;
}
console.log("read", text.length, "characters");
});
console.log("asked for the file");
Terminal: node app.js
asked for the file
could not read: ENOENT
Node's documentation often writes the check as if (err) throw err;, which turns the error into a crash. That is fine for a small script:
app.js
const fs = require("fs");
fs.readFile("nosuch.txt", "utf8", (err, text) => {
if (err) throw err;
console.log(text);
});
Terminal: node app.js
/home/asha/shop/app.js:3
if (err) throw err;
^
[Error: ENOENT: no such file or directory, open 'nosuch.txt'] {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'nosuch.txt'
}
Node.js v22.23.1
This report has no stack. The error was made inside Node's own work, between turns of the loop, when no line of yours was running. Node prints such an error in square brackets, with the place of your throw above it.
The third form: promises, await the result
The third form gives promises. It lives in the module fs/promises, and also as fs.promises.
Inside an async function, or at the top of an ES module, await waits for the file without stopping the engine. Other work runs meanwhile, and the code still reads from top to bottom:
app.mjs
import { readFile, writeFile } from "node:fs/promises";
const text = await readFile("readings.txt", "utf8");
const count = text.trim().split("\n").length;
await writeFile("count.txt", count + "\n");
console.log("counted", count);
Terminal: node app.mjs
cat count.txt
counted 3
3
An error becomes a rejected promise, and await turns the rejection back into a throw. So try and catch work as they did in the last section:
app.js
const fs = require("fs/promises");
async function main() {
try {
const text = await fs.readFile("nosuch.txt", "utf8");
console.log(text);
} catch (e) {
console.log("caught", e.code);
}
}
main();
console.log("main has started");
Terminal: node app.js
main has started
caught ENOENT
The call main() ran until its first await, then gave back a promise. The last line printed, and the rest of main ran when the answer about the file came.
Two files at once
Two awaits, one after the other, wait for each file in turn. Promise.all starts both reads together and waits for both. Its results come back in the order you asked for them, whichever file was ready first:
app.mjs
import { readFile } from "node:fs/promises";
const [readings, notes] = await Promise.all([
readFile("readings.txt", "utf8"),
readFile("notes.txt", "utf8"),
]);
console.log(readings.length, notes.length);
Terminal: node app.mjs
27 12
Which form to use
| Form | Looks like | Use it for |
|---|---|---|
| synchronous | const t = fs.readFileSync(f, "utf8"); | start-up, short scripts and tools |
| callback | fs.readFile(f, "utf8", (err, t) => { }); | older code, which you will read often |
| promise | const t = await readFile(f, "utf8"); | new code, servers above all |
All three do the same work, and give the same errors with the same codes. Only the waiting differs.
Where a callback comes in the order of events
A callback runs from the event loop, so the lines after the call always run first. Node's documentation adds that readFile reads a file a piece at a time, letting the loop turn between pieces.
So setImmediate, set at the same moment, runs before the file arrives:
app.js
const fs = require("fs");
fs.readFile("readings.txt", "utf8", () => console.log("3. the file"));
setImmediate(() => console.log("2. setImmediate"));
console.log("1. the program's last line");
Terminal: node app.js
1. the program's last line
2. setImmediate
3. the file
Worked example 6
Rewrite the hot-gauges program of the first section with promises, so that a server could run it without stopping its engine.
What we have: the synchronous program, which reads readings.txt and writes hot.txt
What we need: the same hot.txt, with the engine free while the files are read and written
The plan: import the promise forms, put await before each call, and keep the rest as it was
app.mjs
import { readFile, writeFile } from "node:fs/promises";
const text = await readFile("readings.txt", "utf8");
const hot = text.trim().split("\n")
.map((line) => line.split(" "))
.filter(([, value]) => Number(value) > 60)
.map(([name]) => name);
await writeFile("hot.txt", hot.join("\n") + "\n");
console.log(hot.length, "hot gauges");
Terminal: node app.mjs
cat hot.txt
2 hot gauges
boiler
press
- The functions readFile and writeFile of node:fs/promises take the same arguments as the Sync forms.
- await gives back the string itself, so the code that splits it does not change. This time it is written as a chain of map and filter.
- Top-level await works because the file is an ES module: its name ends in .mjs.
The same hot.txt, with boiler and press. Only the waiting changed.
Check: cat shows the same two names as the synchronous program did, in the same order.
A path that fails: leaving out an await. Then text is a promise, not a string, and text.trim is not a function: a TypeError.
When you are stuck: A callback's data is undefined outside it
Code after fs.readFile runs before the file has been read. Use the data inside the callback, or switch to await.
await outside an async function works only at the top of an ES module: a .mjs file, or a package with "type": "module".
A rejection that nothing catches crashes the program. Put the await inside try and catch.
Your turn
In a callback (err, text), what is err when the read went well?Tap to reveal
- Error-first: the first parameter is for the error.
null.
Which form keeps the code reading from top to bottom, without stopping the engine?Tap to reveal
- Sync stops the engine.
- A callback splits the code into a later part.
The promise form, with await.
node -e 'require("fs").readFile("readings.txt", () => console.log("b")); console.log("a")'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
a
b
- readFile returns at once, before the file is read.
- console.log("a") runs next.
- The callback runs later, from the event loop.
It prints a, then b.
Did you know?
Not Sync in a server
The Sync forms are fine in a script, but Node's own guide warns against them in a server. Its page Don't Block the Event Loop lists the file system among the core modules with expensive synchronous APIs, and says plainly: do not use the synchronous file system APIs. On a network drive such as NFS, it notes, access times can vary widely, and every waiting request would wait too.
Why it fits here: It answers this topic's question: Node's guide says not to use the Sync file functions in a server.
Promises came in Node 10
The promise form is younger than the other two. The Node manual says the promises API was added in Node 10.0.0, at first reachable only as require('fs').promises. It stopped being experimental in 11.14.0 and 10.17.0, and became the module fs/promises in Node 14.0.0. Under the surface, it runs file work on Node's thread pool, off the event loop.
Why it fits here: It dates this topic's third form: fs/promises arrived in Node 10 and became its own module in Node 14.
In one line
Every fs function has three forms: Sync waits, the callback form calls (err, result) later, and fs/promises gives a promise to await. They do the same work and give the same errors.
Paths: finding files from anywhere
At a glance
A relative path starts from the working folder, the folder where the command was typed. That folder can change from one run to the next.
So a program that reads its own files should build their paths from __dirname, the folder that holds the program, with path.join. The path module also takes paths apart: basename gives the last part, extname the ending, dirname the folder, and parse all of them at once. A path built this way works wherever the command is typed.
Take a guess: Does path.basename give the same answer on Windows and on Linux?
Every path so far, such as readings.txt, was relative. Node looks for it starting from the working folder: the folder where you typed node. process.cwd() tells you which folder that is.
Run the same program from another folder, and the same name points somewhere else:
app.js
const fs = require("fs");
console.log("working folder:", process.cwd());
try {
console.log(fs.readFileSync("readings.txt", "utf8").length);
} catch (e) {
console.log(e.code, "for", e.path);
}
Terminal: node app.js
cd ..
node shop/app.js
working folder: /home/asha/shop
27
working folder: /home/asha
ENOENT for readings.txt
The program did not move; the working folder did. The second time, Node looked for /home/asha/readings.txt. A program that needs its own files, such as data that sits beside it, should not depend on where it was started.
__dirname: the program's own folder
In CommonJS, Node gives every module the name __dirname: the folder that holds the module's own file. Build the path from it, and the file is found from anywhere:
app.js
const fs = require("fs");
const path = require("path");
const file = path.join(__dirname, "readings.txt");
console.log(file);
console.log(fs.readFileSync(file, "utf8").split("\n")[0]);
Terminal: cd ..
node shop/app.js
/home/asha/shop/readings.txt
boiler 95
In an ES module, the same folder is import.meta.dirname, as lesson 02 showed. Its name for the file itself is import.meta.filename, and in CommonJS it is __filename.
The path module
The built-in module path joins paths and takes them apart. It works on the text alone and never looks at the disk. Here are its most used functions:
app.js
const path = require("path");
console.log(path.join("logs", "2026", "..", "today.txt"));
console.log(path.resolve("logs", "today.txt"));
console.log(path.basename("/home/asha/shop/report.txt"));
console.log(path.extname("report.txt"), path.dirname("/home/asha/shop/report.txt"));
console.log(path.relative("/home/asha/shop", "/home/asha/logs/a.txt"));
Terminal: node app.js
logs/today.txt
/home/asha/shop/logs/today.txt
report.txt
.txt /home/asha/shop
../logs/a.txt
| Function | Gives | Example answer |
|---|---|---|
path.join(a, b, ...) | the parts joined with /, with .. and doubled slashes tidied | logs/today.txt |
path.resolve(a, b, ...) | a full path, starting from the working folder | /home/asha/shop/logs/today.txt |
path.basename(p) | the last part: the file's name | report.txt |
path.basename(p, ".txt") | the name without that ending | report |
path.extname(p) | the ending, from the last dot | .txt |
path.dirname(p) | everything before the last part | /home/asha/shop |
path.relative(from, to) | the way from one path to the other | ../logs/a.txt |
path.parse gives every part at once, in an object:
app.js
const path = require("path");
console.log(path.parse("/home/asha/shop/report.txt"));
Terminal: node app.js
{
root: '/',
dir: '/home/asha/shop',
base: 'report.txt',
ext: '.txt',
name: 'report'
}
Why not join with +
A path built with + is easy to get wrong. Two parts that both have a slash give a doubled slash, which usually still works; two that have none run together, which never does.
And Windows writes \ between folders, not /. path.join handles all three, and path.sep is the separator of the system the program runs on:
app.js
const path = require("path");
const dir = "logs/";
console.log(dir + "/" + "today.txt");
console.log("logs" + "today.txt");
console.log(path.join(dir, "today.txt"));
console.log(path.sep);
Terminal: node app.js
logs//today.txt
logstoday.txt
logs/today.txt
/
Worked example 7
For every .txt file in the logs folder, the clerk wants a .json file beside it, holding its lines as an array: today.txt gives today.json. Build every path with the path module.
What we have: a logs folder beside app.js, with old.txt and today.txt in it
What we need: old.json and today.json in logs, whatever folder the program is started from
The plan: find the folder from __dirname; for each .txt name, read its lines, build the new name from the old one, and write the JSON
app.js
const fs = require("fs");
const path = require("path");
const dir = path.join(__dirname, "logs");
for (const name of fs.readdirSync(dir)) {
if (path.extname(name) !== ".txt") continue;
const lines = fs.readFileSync(path.join(dir, name), "utf8").trim().split("\n");
const json = path.join(dir, path.basename(name, ".txt") + ".json");
fs.writeFileSync(json, JSON.stringify(lines) + "\n");
console.log(path.relative(__dirname, json));
}
Terminal: node app.js
cat logs/today.json
logs/old.json
logs/today.json
["boiler 95"]
path.extname(name)picks out the .txt files, and continue skips everything else.path.basename(name, ".txt")gives today, and adding .json gives the new name.path.join(dir, ...)puts the folder in front, so the program works from any folder.path.relativeprints each new file's path short, from the program's folder.
logs now holds old.json and today.json.
Check: cat logs/today.json shows the one line of today.txt, inside an array.
A path that fails: building the new name with name.replace("txt", "json"). It changes the first txt anywhere in the name, so a file called txt-notes.txt would become json-notes.txt.
When you are stuck: A file is found from one folder but not from another
Print process.cwd(). A relative path starts there.
Build paths to the program's own files from __dirname, or from import.meta.dirname in an ES module.
Print the path you built before you use it. A missing slash or an extra .. shows at once.
Your turn
What does path.extname("report.tar.gz") give?Tap to reveal
- The ending starts at the last dot.
".gz".
In CommonJS, which name holds the folder of the module's own file?Tap to reveal
- In an ES module it is import.meta.dirname.
__dirname.
node -p 'require("path").join("a", "..", "b", "c.txt")'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
b/c.txt
- The .. cancels the a before it.
- What is left is b, then c.txt.
It prints b/c.txt.
Did you know?
One module, two kinds of path
The path module follows the system it runs on. The Node manual says that on Windows it assumes Windows-style paths, with backslashes. Its example: path.basename('C:\\temp\\myfile.html') gives myfile.html on Windows, but the whole string back on POSIX, where a backslash is not a separator. path.posix and path.win32 force one style on any system.
Why it fits here: It answers this topic's question: path follows the running system, so basename can differ between Windows and Linux.
From a file URL to a path
ES modules name their own file as a URL, not a path. The Node manual describes url.fileURLToPath, added in Node 10.12.0, which turns a file: URL into an ordinary path. It decodes characters written as percent codes and makes sure the result is a valid absolute path on any system. So fileURLToPath(import.meta.url) gives the module's own path.
Why it fits here: It adds to this topic's paths: fileURLToPath turns an ES module's file URL into a path that fs can use.
Source: Node.js manual: URL
In one line
A relative path starts from the working folder, which can change. Build paths to a program's own files from __dirname with path.join, and take paths apart with basename, extname, dirname and parse.
Where it is used
Almost every program reads or writes a file somewhere. Here is where each idea of this lesson does its work.
| What you learned | Where it is used | A real example |
|---|---|---|
| reading and writing text | logs, reports and settings | a web server that adds one line to its log for every request |
| Buffers | files that are not text | a program that makes small copies of photos |
| JSON files | a small program's data | package.json itself, read by npm |
| folders | tools that set things up and tidy | a command that makes a new project's folders |
| error codes | programs that must keep running | a server that answers Not found when a page's file is missing |
| the three forms | Sync in tools, promises in servers | a build script, and the server it builds |
| path and __dirname | programs started from any folder | a command-line tool, run in whatever folder you are in |
The Foreman's ledgers are files. The marks on a page are bytes, and the tidy form the engine keeps its counts in is JSON. The drawers are folders, a full address is a path, and the runner sent for a ledger is a callback or a promise.
Mistakes and debugging
These are the slips that people meet most often with files. Every output below is the real one, from the code shown.
1. Text without its encoding
app.js
const fs = require("fs");
const data = fs.readFileSync("readings.txt");
try {
data.split("\n");
} catch (e) {
console.log(e.message);
}
Terminal: node app.js
data.split is not a function
Without an encoding, readFileSync gives a Buffer, which has no split. The fix: fs.readFileSync("readings.txt", "utf8").
2. Writing when you meant to add
app.js
const fs = require("fs");
for (const event of ["engine started", "boiler hot", "pump low"]) {
fs.writeFileSync("log.txt", event + "\n");
}
Terminal: node app.js
cat log.txt
pump low
Each writeFileSync replaced the whole file, so only the last line is left. The fix: appendFileSync, which adds.
3. Lines that run together
app.js
const fs = require("fs");
fs.appendFileSync("log.txt", "boiler hot");
fs.appendFileSync("log.txt", "pump low");
Terminal: node app.js
cat log.txt
boiler hotpump low
Neither call adds a newline. The fix: end every line with \n yourself: "boiler hot\n".
4. An object written without JSON
app.js
const fs = require("fs");
const pump = { name: "pump 2", pressure: 3.5 };
try {
fs.writeFileSync("pump.json", pump);
} catch (e) {
console.log(e.code);
console.log(e.message);
}
Terminal: node app.js
ERR_INVALID_ARG_TYPE
The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of Object
A file holds text or bytes, never an object. The fix: fs.writeFileSync("pump.json", JSON.stringify(pump)).
5. A callback's result used outside it
app.js
const fs = require("fs");
let text;
fs.readFile("readings.txt", "utf8", (err, t) => {
text = t;
console.log("inside:", text.length);
});
console.log("outside:", text);
Terminal: node app.js
outside: undefined
inside: 27
The last line ran before the file was read. The fix: use the text inside the callback, or read it with await.
6. A rename into a folder
app.js
const fs = require("fs");
fs.mkdirSync("archive");
try {
fs.renameSync("readings.txt", "archive");
} catch (e) {
console.log(e.message);
}
Terminal: node app.js
EISDIR: illegal operation on a directory, rename 'readings.txt' -> 'archive'
Unlike mv, renameSync does not put a file inside a folder that you name. The fix: give the full new path, "archive/readings.txt", built with path.join.
7. rmSync on a folder
app.js
const fs = require("fs");
try {
fs.rmSync("logs");
} catch (e) {
console.log(e.code);
console.log(e.message);
}
Terminal: node app.js
ERR_FS_EISDIR
Path is a directory: rm returned EISDIR (is a directory) logs
Like rm without -r, rmSync refuses a folder. The fix: fs.rmSync("logs", { recursive: true }), when you are sure.
The debugging corner: what is really on the disk?
When a file operation surprises you, print three things: process.cwd(), the path you built, and e.code. Then look in the terminal: ls -l shows the files and their sizes, and cat -A marks the end of every line with $, so a missing newline shows at once.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
app.js
const fs = require("fs");
const path = require("path");
const file = path.join(__dirname, "pump.json"); // a path that works from anywhere
let pump = { runs: 0 };
try {
pump = JSON.parse(fs.readFileSync(file, "utf8")); // text, then data
} catch (e) {
if (e.code !== "ENOENT") throw e; // only "missing" is expected
}
pump.runs += 1;
fs.writeFileSync(file, JSON.stringify(pump) + "\n"); // written back whole
console.log(pump);
Terminal: node app.js
node app.js
{ runs: 1 }
{ runs: 2 }
| When you see | It means | Do |
|---|---|---|
<Buffer 62 6f ...> | the file was read as bytes | add "utf8" |
ENOENT | a file or folder is missing | check the path, process.cwd() and __dirname |
EEXIST | it is already there | { recursive: true } for mkdirSync |
EISDIR | a folder where a file was expected | check the name; give rename the full new path |
ENOTEMPTY | the folder still holds files | rmSync with { recursive: true } |
ERR_INVALID_ARG_TYPE | an argument of the wrong kind | JSON.stringify an object; look for undefined |
| a SyntaxError from JSON.parse | the text is not JSON | print the text; double quotes, no last comma |
undefined after a callback | the file was not read yet | use it inside the callback, or await |
The story: Ledgers that last
You teach the engine the ledger room. It learns to write a page and to add a line, to read a page as words or as plain marks, and to keep its counts in a tidy form that it can read back. It learns the drawers, and their full addresses. It learns to send a runner for a ledger and carry on meanwhile.
Next week the engine stops for oiling again. It starts by reading its ledger, and not one reading is lost.
The Foreman nods. "Next," she says, "the bells: how one part of the hall tells the others that something has happened."
Reagents gathered: fs, encoding, Buffer, JSON, error code, path.
Sources
- The Node.js documentation (Not stated for the docs in the Node.js LICENSE file (read 2026-10-26); facts and ideas only)
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)