fs Module (Node.js)
fs is Node.js's built-in File System module for reading, writing, and managing files and directories. It offers async (callback), Promise (fs/promises), and synchronous (Sync) versions of each operation.
Node.js
fs is how Node touches the disk. It covers reading and writing files (readFile/writeFile), appending, deleting (unlink), renaming, creating and listing directories (mkdir, readdir), checking existence and metadata (stat), and streaming large files (createReadStream/createWriteStream).
Every operation comes in three styles. The async callback form (fs.readFile(path, cb)) is non-blocking. The Promise form (const fs = require('fs/promises'); await fs.readFile(path)) is the cleanest with async/await. The synchronous form (fs.readFileSync) blocks the event loop and should be reserved for startup scripts and CLIs, never inside a server handling requests.
Pair fs with the path module to build cross-platform file paths, and prefer streaming for large files so you do not load gigabytes into memory at once.
Syntax
const fs = require("fs/promises");
await fs.readFile(path, "utf8");Examples
JavaScript
const fs = require("fs/promises");
async function run() {
await fs.writeFile("note.txt", "hello");
const text = await fs.readFile("note.txt", "utf8");
console.log(text);
}
run();Output:
hello