Core Modules
Node.js fs File System Module
The fs module reads and writes files. It offers three APIs: promise-based under fs/promises (the modern default), callback-based, and synchronous methods suffixed with Sync that block the event loop.
What is fs File System Module in Node.js?
The fs module reads and writes files. It offers three APIs: promise-based under fs/promises (the modern default), callback-based, and synchronous methods suffixed with Sync that block the event loop.
fs File System Module example
import { readFile, writeFile, appendFile, mkdir, readdir, stat } from 'node:fs/promises';
const text = await readFile('data.json', 'utf8');
const data = JSON.parse(text);
await writeFile('out.json', JSON.stringify(data, null, 2));
await appendFile('app.log', 'started\n');
await mkdir('uploads', { recursive: true });
const files = await readdir('./uploads');
const info = await stat('data.json');
console.log(info.size, info.isDirectory());How this works
Passing "utf8" returns a string; without it you get a Buffer. recursive: true on mkdir creates intermediate directories and does not throw when the directory already exists.
Key points to remember
- Prefer fs/promises with async/await in new code.
- Sync methods are acceptable at startup, never inside a request handler.
- Use streams for large files instead of reading them entirely into memory.
- Handle ENOENT explicitly — a missing file is a normal condition, not a crash.
Common mistakes with fs File System Module
- readFileSync inside an HTTP handler, which blocks every other request.
- Reading a multi-gigabyte file with readFile and exhausting memory.
- Checking existence with fs.exists before opening, which races — just open and catch.
Node.js fs File System Module— Interview Questions & FAQs
What is the difference between readFile and readFileSync?+
readFile is asynchronous and lets the event loop continue serving other work. readFileSync blocks the entire process until the read finishes, so it must never appear in a request path.
