Skip to content
Node.js

fs Module

Read, write, and watch files with promises and callbacks.

By EZ4Code Team
fsfilestream

Code

import { promises as fs } from "fs";
import { watch } from "fs";

// Async/await with promises API
async function readJson(path) {
  const raw = await fs.readFile(path, "utf8");
  return JSON.parse(raw);
}

// Write a file atomically (write to temp, rename)
async function writeJson(path, data) {
  const tmp = path + ".tmp";
  await fs.writeFile(tmp, JSON.stringify(data, null, 2));
  await fs.rename(tmp, path);
}

// Streaming a large file
import { createReadStream, createWriteStream } from "fs";
createReadStream("input.bin")
  .pipe(createWriteStream("output.bin"))
  .on("finish", () => console.log("done"));

// Watch a file for changes
watch("./config.json", (eventType, filename) => {
  console.log(eventType, filename);
});

Explanation

Node's fs.promises API offers async/await-friendly file operations without callback pyramids. Writing to a temp file and renaming is atomic on POSIX, preventing partial reads. createReadStream pipes large files in chunks, avoiding loading them entirely into memory.

More Node.js Snippets