Reading files with fs.readFile
A file is the first thing a program can leave behind, and Node.js keeps the file system in node:fs and in its promise twin node:fs/promises. Both read the same bytes: with an encoding the bytes arrive as text, without one they arrive as a Buffer. The difference between the two modules is only how the program waits.
The lesson reads one file with a callback and with await, then reads two files at once and looks at the bytes behind the characters. The last program asks for a file that is not there, which is the error every program that opens a path has to expect. All four programs work in a folder made with fs.mkdtemp and remove it before they end, so nothing is left on the disk.
readFile with a callback
readFile(path, encoding, callback) starts the read and returns at once, and the callback runs later with an error or with the text. The encoding is what turns the bytes into a string: 'utf8' is the one a text file wants, and it is also the default of the write functions.
The program makes a folder, writes two lines into a file and reads it back. The callback counts the lines and removes the folder before it prints that the folder is gone.
The file read.mjs:
import { existsSync, mkdtempSync, readFile, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = mkdtempSync(join(tmpdir(), 'read-'));
const file = join(dir, 'notes.txt');
writeFileSync(file, 'alpha\nbeta\n');
readFile(file, 'utf8', (error, text) => {
if (error) {
throw error;
}
const lines = text.split('\n').filter((line) => line !== '');
console.log('the text is a', typeof text);
console.log('lines:', lines.length);
console.log('characters:', text.length);
rmSync(dir, { force: true, recursive: true });
console.log('the folder is gone:', !existsSync(dir));
});
node read.mjs
the text is a string
lines: 2
characters: 11
the folder is gone: true
The text arrived as a string, which is what the encoding asked for, and the two lines were counted by splitting on the newline and dropping the empty tail. The file was prepared with writeFileSync because writing is the next lesson; the read itself never waited, since the callback did all the work.
The promise form
The same function in node:fs/promises returns a promise instead of taking a callback, so await can wait for it and a try can catch its error. Two reads can be started together with Promise.all, which is the reason the promise form exists: a callback per file is a nesting, a promise per file is a list.
The program reads two files in one wait and prints a line from each. The last check shows that neither read dropped the newline at the end of its file.
The file promises.mjs:
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'read-'));
await writeFile(join(dir, 'a.txt'), 'one\ntwo\n');
await writeFile(join(dir, 'b.txt'), 'three\n');
const [first, second] = await Promise.all([
readFile(join(dir, 'a.txt'), 'utf8'),
readFile(join(dir, 'b.txt'), 'utf8'),
]);
console.log('the first file has', first.trimEnd().split('\n').length, 'lines');
console.log('the second file says:', second.trimEnd());
console.log('both texts end with a newline:', first.endsWith('\n') && second.endsWith('\n'));
await rm(dir, { force: true, recursive: true });
console.log('the folder is gone');
node promises.mjs
the first file has 2 lines
the second file says: three
both texts end with a newline: true
the folder is gone
Both reads were started before either had finished, and the program waited once for the pair. The difference against the callback is not speed but shape: a function that reads three files is three await lines in a row, or one Promise.all when the files do not depend on each other. The lesson on promise combinators covers the rest of that list.
Bytes and characters
Without an encoding, readFile answers with a Buffer: the bytes of the file, in order, with a length that counts bytes and not characters. A character outside ASCII takes more than one byte in UTF-8, so the two numbers differ as soon as the text has an accent, a Cyrillic letter or an emoji.
The program writes four characters, one of them accented, and reads the same file twice. The first read gives six bytes and the second gives four characters, and the text is printed in quotes so that the newline at the end is visible.
The file encoding.mjs:
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'read-'));
const file = join(dir, 'word.txt');
await writeFile(file, 'caf\u00e9\n');
const buffer = await readFile(file);
const text = await readFile(file, 'utf8');
console.log('without an encoding it is a buffer:', Buffer.isBuffer(buffer));
console.log('the bytes:', buffer.length);
console.log('the characters:', text.trimEnd().length);
console.log('the text:', JSON.stringify(text));
await rm(dir, { force: true, recursive: true });
node encoding.mjs
without an encoding it is a buffer: true
the bytes: 6
the characters: 4
the text: "café\n"
The letter é costs two bytes in UTF-8, which is the whole difference between six and four. The lesson on Unicode and length goes further into the counting; for a file the rule is that an encoding is a promise about the bytes, and utf8 is the one to name unless the file says otherwise.
A missing file
A path that does not exist is a rejection with a code of ENOENT, not a crash. The code is the part to match on, because the message text comes from the operating system and a program should not depend on its wording. The program prints the first part of the message, up to the comma, and sets an exit status so the shell can tell that the run failed; the rest of the message names the folder of this run and is left out for that reason.
The file missing.mjs:
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'read-'));
try {
await readFile(join(dir, 'no-such-file.txt'), 'utf8');
} catch (error) {
console.log('the name of the error:', error.name);
console.log('the code:', error.code);
console.log('the message:', error.message.split(',')[0]);
process.exitCode = 1;
} finally {
await rm(dir, { force: true, recursive: true });
}
console.log('the program is done, the exit code is', process.exitCode);
node missing.mjs
echo "exit code: $?"
the name of the error: Error
the code: ENOENT
the message: ENOENT: no such file or directory
the program is done, the exit code is 1
exit code: 1
The read rejected with a plain Error whose code is ENOENT, and the program printed the code, the beginning of the message and its own line after the finally. It exits with one because of process.exitCode, which is the subject of the lesson on process. An error that is expected should be caught like this; one that is not should be left to end the program, which the next lessons show as well.
Exercises
- Read a file without an encoding and print the first three bytes as numbers.
- Count the lines of a file that does not end with a newline. What does the split give you, and does the count change?
- Read one file as utf8 and as latin1 and print both texts. Which characters survive the second encoding?
- Catch the error of a missing file and print its path property. Which part of that path is the file name?
- Replace the callback read with readFileSync. What does the program do while the call runs, and what does it lose?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does readFile hand to its callback when no encoding is given?
Answer
A Buffer with the bytes of the file
The bytes are the raw answer; an encoding is what turns them into a string.
-
Where does the promise form of readFile live?
Answer
In node:fs/promises
The runtime ships both modules, and the second one returns promises instead of taking a callback.
-
What does this program print?
const text = "café"; console.log(Buffer.byteLength(text), text.length);Answer
5 4
The accented letter is one character and two bytes, so the file has to hold five bytes.
-
What is the code of the error for a file that does not exist?
Answer
ENOENT
The name is short for no such entity, and it is the value a program compares.
-
What does the callback form of readFile return?
Answer
undefined; the text arrives in the callback
The call only starts the read; the result is handed to the callback later.
-
What does this program print?
const text = "one\ntwo\n"; console.log(JSON.stringify(text.trimEnd().split("\n")));Answer
["one","two"]
trimEnd removes the last newline, so the split finds two lines and no empty tail.
-
Why does readFile need an encoding for text?
Answer
Without one it returns bytes, and bytes are not text
A file holds bytes; the encoding is the rule that turns them into characters.
-
What does this program print?
const buffer = Buffer.from("hi"); console.log(buffer.length, buffer.toString("utf8"));Answer
2 hi
Two ASCII letters are two bytes, and toString decodes them back to the same text.
-
What does the lesson do with the folder it creates?
Answer
It removes it before the program ends
A folder under the system temporary directory is removed by the program that made it.
-
What does this program print?
import { readFile } from "node:fs/promises"; try { await readFile("/no/such/folder/notes.txt", "utf8"); } catch (error) { console.log(error.code); }Answer
ENOENT
The promise rejects with a code that names the reason, and the catch prints it.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev