AceDevHub
Beginner Node.js Interview QuestionsBeginnerPractical

Node.js · Question 25

How do you read and write files in Node.js?

Direct answer

Use fs.promises.readFile/writeFile for async Promise-based I/O, or fs.createReadStream for large files — avoid readFileSync on servers; handle errors with try/catch and validate paths.

The fs module wraps libuv file operations (Q8–10). Promises API fits async/await handlers; streams fit large JSON imports like AceDevHub interview content files.

APIStyleWhen
fs.promises.readFileAsync PromiseSmall/medium files, JSON config
fs.readFile + callbackAsync callbackLegacy codebases
fs.readFileSyncBlocking syncCLI scripts at startup only
fs.createReadStreamStreamLarge files, line-by-line parsing
fs.promises.writeFileAsync PromiseSave output, generate files
  • Encoding — 'utf8' returns string; omit encoding for Buffer binary.
  • JSON.parse — wrap readFile + parse in try/catch; invalid JSON throws.
  • Permissions — EACCES and ENOENT need user-friendly errors; do not leak paths in public API.
fs-read-write.mjs
import fs from "node:fs/promises";
import path from "node:path";

async function loadInterviewJson(relativePath) {
  const fullPath = path.resolve(relativePath);
  const raw = await fs.readFile(fullPath, "utf8");
  return JSON.parse(raw);
}

async function saveReport(dir, filename, data) {
  await fs.mkdir(dir, { recursive: true });
  await fs.writeFile(
    path.join(dir, filename),
    JSON.stringify(data, null, 2),
    "utf8"
  );
}