← Back to TypeScript Course | Chapter 13: TypeScript with Node.js | Lesson 3 of 6

File System with Types

Node.js provides the fs module for reading, writing, and managing files. TypeScript adds type safety around file paths, contents, and asynchronous file operations.
Syntax
typescript
import * as fs from "fs";
const data: string = fs.readFileSync("path", "utf-8");
fs.writeFileSync("path", data);

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

typescript
// 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

typescript
// 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

typescript
// 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

typescript
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

typescript
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);
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Treating readFileSync("data.txt") as a string, when without an encoding it returns a Buffer.
  2. Using JSON.parse on the file text and trusting the result, since it is any and must be validated.
  3. Using sync methods in a busy server, which blocks the event loop.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.