Sub topic 8
Reading files asynchronously
This chapter adds the part of wcl that touches the disk. You will read a file with readFile from node:fs/promises, turn low-level failures into readable messages, and read several files without blocking. It assumes you have finished the earlier chapters. That means a project with "type": "module", the NodeNext compiler settings, and a pure countText function in src/count.js. You should also be comfortable with async/await and with try/catch.
Why file reads are asynchronous
Reading a file means asking the operating system for data. The data may come from a slow disk or a network mount, so the answer is not instant. Node.js offers two styles of file API:
- Synchronous functions such as
readFileSyncblock the whole process until the read finishes. - Promise-based functions in
node:fs/promiseshand the work to the system and let Node run other code until the result is ready.
A one-shot tool that reads a single file would work fine with the synchronous version. The promise-based version is still the better habit, for three reasons:
- It composes with
async/await. - It lets you read several files at once.
- It carries over to code that later becomes a server, where blocking one request stalls every other request.
The basic call
readFile takes a path and an optional encoding, and returns a promise.
import { readFile } from "node:fs/promises";
const text = await readFile("notes.txt", "utf8");
console.log(text.length);The second argument controls the result type. TypeScript knows this from the overloads in @types/node:
| Call | Resolves to |
|---|---|
| `readFile(path, "utf8")` | `string` |
| `readFile(path)` | `Buffer` (raw bytes) |
Pass the encoding when you want text. Without it you get a Buffer, and calling string methods on it fails to compile.
The top-level await above is legal because of your configuration. It needs an ES module, which comes from "type": "module" in package.json. It also needs a compiler target and module setting that support it, which ES2022 and NodeNext do. In a CommonJS project you would wrap the call in an async function.
What happens during a read
The sequence below shows what happens when your code calls readFile.
The promise settles in one of two ways. It resolves with the whole file contents, or it rejects with an Error object. Node loads the entire file into memory before the promise resolves. There is no partial result.
Turning errors into messages
A rejected readFile produces an error whose message looks like this:
ENOENT: no such file or directory, open 'missing.txt'That is accurate, but it is not what a user of your tool expects to see. The error also carries a code property with a short string, and you can branch on it. These are the codes you will meet most often:
| Code | Meaning | Typical cause |
|---|---|---|
| `ENOENT` | No such file or directory | Typo in the path |
| `EISDIR` | Path is a directory | Running `wcl src` |
| `EACCES` | Permission denied | File owned by another user |
| `EMFILE` | Too many open files | Reading thousands of files at once |
TypeScript types a caught value as unknown, so you must narrow it before reading code. A small type guard keeps that logic in one place. Put this in src/read.ts:
import { readFile } from "node:fs/promises";
export function isErrnoException(err: unknown): err is NodeJS.ErrnoException {
return err instanceof Error && "code" in err;
}
export async function readTextFile(path: string): Promise<string> {
try {
return await readFile(path, "utf8");
} catch (err) {
if (isErrnoException(err)) {
switch (err.code) {
case "ENOENT":
throw new Error(`${path}: no such file`, { cause: err });
case "EISDIR":
throw new Error(`${path}: is a directory`, { cause: err });
case "EACCES":
throw new Error(`${path}: permission denied`, { cause: err });
}
}
throw err;
}
}Three details here are easy to miss:
return awaitinside thetryis deliberate. A plainreturn readFile(...)would hand the promise back before it settles, and thecatchblock would never see the rejection.- The
{ cause: err }option keeps the original error attached to the new one. It is available because the target isES2022. A debugger or a verbose mode can print the original system error when you need it. - Codes you do not recognize fall out of the
switchand are rethrown unchanged. Do not swallow errors you cannot explain.
Handling ENOENT by catching it is more reliable than checking existsSync first. Between the check and the read, another process can delete the file. Checking first only gives you a second place for the same failure.
Using it in main
The entry point stays small. It validates arguments, calls the reader, passes the text to the pure function, and prints. With the helper in place, the main function from the earlier chapter simplifies:
import { countText } from "./count.js";
import { readTextFile } from "./read.js";
async function main(argv: string[]): Promise<number> {
const file = argv[0];
if (!file) {
console.error("usage: wcl <file>");
return 2;
}
try {
const text = await readTextFile(file);
const { lines, words } = countText(text);
console.log(`${lines} ${words} ${file}`);
return 0;
} catch (err) {
console.error(`wcl: ${err instanceof Error ? err.message : String(err)}`);
return 1;
}
}
process.exitCode = await main(process.argv.slice(2));Note the .js extension in the import paths. With NodeNext, TypeScript requires the extension of the compiled file, even though the source file is .ts. The error-handling chapter returns to the exit codes in detail. Here, only note that all file failures funnel into one catch and one exit code.
Reading several files
A real wc accepts many files. The reads are independent, so you can start them together instead of waiting for each one in turn. Promise.all does this, but it rejects as soon as any one promise rejects. One missing file would then hide the results for all the others.
Promise.allSettled waits for every promise and reports each outcome. That fits a tool where one bad path should not stop the rest:
import { countText } from "./count.js";
import { readTextFile } from "./read.js";
export async function countFiles(files: string[]): Promise<number> {
const results = await Promise.allSettled(files.map((f) => readTextFile(f)));
let failures = 0;
results.forEach((result, i) => {
const file = files[i];
if (result.status === "fulfilled") {
const { lines, words } = countText(result.value);
console.log(`${lines} ${words} ${file}`);
} else {
failures += 1;
const reason = result.reason;
console.error(
`wcl: ${reason instanceof Error ? reason.message : String(reason)}`,
);
}
});
return failures === 0 ? 0 : 1;
}Promise.allSettled returns results in the same order as the input, so index i lines up with files[i]. Output stays in the order the user typed, even though reads may finish in any order.
Edge cases to know about
Invalid UTF-8. Decoding with "utf8" never throws. Bytes that are not valid UTF-8 become the replacement character U+FFFD. A binary file, such as an image, therefore "succeeds" and produces meaningless counts. If you care, you can detect a null byte in the Buffer and refuse the file.
Byte order mark. Some Windows editors write a U+FEFF mark at the start of a UTF-8 file. readFile keeps it as the first character of the string. Your countText is unaffected, because \s in a JavaScript regular expression matches U+FEFF, but code that compares the first characters of a file would see it.
Line endings. Windows files end lines with \r\n. Splitting on "\n" still gives the right line count, and the leftover \r counts as whitespace between words.
Empty files. readFile resolves with an empty string. The countText tests from the testing chapter cover this case with lines: 0, words: 0.
Large files. readFile holds the whole file in memory. For files in the hundreds of megabytes, a stream is a better fit, since it processes the data in chunks. The stdin chapter introduces streams, and the same approach applies to createReadStream.
Relative paths. A relative path resolves against the current working directory of the process, not against the folder that holds your script. Run wcl notes.txt from another directory and Node looks for notes.txt there. This is what users expect from a command-line tool.
Keeping the read at the edge
The design rule behind this chapter is that I/O lives in read.ts and main, and logic lives in count.ts. countText takes a string and returns numbers. It never learns where the string came from. That separation pays off in two ways:
- You can test counting with literal strings, with no temporary files.
- You can later feed it text from standard input without changing it.
If you later want to test readTextFile itself, write a temporary file with mkdtemp and writeFile from node:fs/promises, and assert on the error messages. Keep those tests few. The file system is the slow, fragile part, and the pure function carries most of the logic.
Exercise
Why does readTextFile use return await readFile(path, "utf8") inside the try block instead of return readFile(path, "utf8")?
Show answer
Without await, the function returns the pending promise immediately and leaves the try block before the promise settles. If the read later rejects, the rejection goes to the caller and the catch block never runs, so the friendly error messages would be skipped. return await keeps the function inside the try until the promise settles, so the catch can handle the rejection.
Exercise
You run wcl a.txt missing.txt b.txt using countFiles, and missing.txt does not exist. What is printed to stdout, what is printed to stderr, and what exit code is returned? What would change if you used Promise.all instead of Promise.allSettled?
Show answer
Stdout gets the counts for a.txt and b.txt, in that order. Stderr gets wcl: missing.txt: no such file. The function returns 1 because one read failed. With Promise.all, the first rejection would reject the whole call, so no counts for a.txt or b.txt would be printed. You would get only the one error.