File System with Types
In this page:
Reading a File
Reading a file with fs.readFileSync typed against @types/node returns a Buffer by default, or a string if you pass an encoding like utf-8 as the second argument — the return type actually changes based on that argument.
Example: Reading a File
// import * as fs from "fs";
// const buffer: Buffer = fs.readFileSync("data.txt");
// const text: string = fs.readFileSync("data.txt", "utf-8");
console.log("readFileSync's return type depends on the encoding argument");
Writing Files
Writing files with fs.writeFileSync accepts either a string or a Buffer as the data argument, and the typed signature ensures you can't accidentally pass something like a plain object without converting it first.
Example: Writing Files
// import * as fs from "fs";
// fs.writeFileSync("out.txt", "hello");
console.log("writeFileSync accepts a string or Buffer as its data argument");
Checking File Information
Checking file information with fs.statSync returns a typed Stats object exposing properties like .isFile(), .isDirectory(), and .size, letting you branch on what kind of filesystem entry you're actually looking at.
Example: Checking File Information
// import * as fs from "fs";
// const stats: fs.Stats = fs.statSync("data.txt");
// if (stats.isFile()) { console.log(stats.size); }
console.log("statSync returns a typed Stats object with isFile()/isDirectory()");
Typed File Data
Typed file data means treating whatever you read back from disk — especially JSON files — the same way as any other untyped external input: parse it, then validate its shape before trusting it matches an interface.
Example: Typed File Data
interface Config { debug: boolean }
// const raw = fs.readFileSync("config.json", "utf-8");
const raw = '{"debug": true}';
const config: Config = JSON.parse(raw);
console.log(config.debug);
Handling File Errors
Handling file errors means catching exceptions from these synchronous calls (or rejected promises from their async counterparts) and narrowing the caught value from unknown, since Node's fs errors carry a .code property like ENOENT that plain Error doesn't guarantee.
Example: Handling File Errors
try {
// fs.readFileSync("missing.txt");
throw { code: "ENOENT", message: "file not found" };
} catch (err: unknown) {
const e = err as { code?: string };
console.log("Error code:", e.code);
}
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: