Sub topic 8
Reading Files Asynchronously
This chapter assumes you know basic TypeScript, async and await, Node.js modules, and how a command-line program receives arguments. The previous chapter established the entry point and argument parsing. Here, you will connect a file argument to asynchronous file reading.
Why asynchronous file I/O matters
File reading is input/output, or I/O. The program must wait for the operating system to retrieve data from storage. A synchronous read blocks the Node.js process until the operation finishes. That can make a command unresponsive, especially when it reads large files or runs alongside other work.
Node.js provides asynchronous APIs in node:fs/promises. These functions return promises. An async function can wait for the promise with await while keeping the rest of the runtime available for other tasks.
The readFile function reads the complete file:
import { readFile } from "node:fs/promises";
const text = await readFile("notes.txt", "utf8");
console.log(text);The "utf8" option is important. Without it, readFile returns a Buffer, which represents raw bytes. With it, the result is a string.
Read the file named by the user
A command-line tool should treat the file path as untrusted input. First, validate that the user supplied a path. Then read the file inside a try block so expected failures can be reported clearly.
import { readFile } from "node:fs/promises";
async function main(argv: string[]): Promise<number> {
const file = argv[0];
if (!file) {
console.error("usage: wcl <file>");
return 2;
}
try {
const text = await readFile(file, "utf8");
console.log(`Read ${text.length} characters from ${file}`);
return 0;
} catch (error) {
console.error(`Could not read ${file}: ${formatError(error)}`);
return 1;
}
}
function formatError(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
process.exitCode = await main(process.argv.slice(2));process.argv.slice(2) removes the Node.js executable path and the script path. The remaining values are the arguments entered by the user.
The main function returns a number rather than terminating the process immediately. The entry point assigns that number to process.exitCode. This lets pending output finish before Node.js exits.
Understand common read failures
readFile rejects its promise when it cannot read the path. Common causes include:
| Failure | Typical cause | Useful response |
|---|---|---|
| `ENOENT` | The path does not exist | Tell the user the file was not found |
| `EACCES` | The process lacks permission | Tell the user access was denied |
| `EISDIR` | The path names a directory | Ask for a regular file |
Node.js errors often include a code property. You can inspect it without assuming every thrown value has the same shape.
function errorCode(error: unknown): string | undefined {
if (
error !== null &&
typeof error === "object" &&
"code" in error &&
typeof error.code === "string"
) {
return error.code;
}
return undefined;
}Use this helper when you want stable, user-focused messages. Keep the original error available for unexpected failures, because its message can help diagnose permission, encoding, or operating-system problems.
Follow the data flow
A complete-file read is a good fit for a small counting tool. For very large files, loading everything into memory may be wasteful. A later design could use a readable stream and process chunks as they arrive. That changes the counting logic, so begin with readFile when the input size is reasonable.
Exercise
What type does readFile return when you omit the "utf8" argument, and what type does it return when you include it?
Show answer
It returns a Buffer without an encoding. With "utf8", it returns a string.