In Node.js, the cleanest way to write text or JSON data to files is using fs/promises (writeFile and mkdir) with async/await so you do not block the event loop. For JSON data, serialize the object first with JSON.stringify(data, null, 2) before passing the resulting string to writeFile().


1. Writing Plain Text with fs/promises (writeFile)

Use await writeFile(filePath, text, "utf8") inside an async function to write or overwrite a text file asynchronously:

// Write plain text to a file asynchronously using Node.js fs/promises
import { writeFile } from "node:fs/promises";

async function saveTextLog(filePath, message) {
  await writeFile(filePath, message, "utf8");
  console.log("Saved text file:", filePath);
}

saveTextLog("./output/status.txt", "Pipeline finished cleanly.\n").catch((err) => {
  console.error("Failed to write text file:", err);
});
  • node:fs/promises: Provides Promise-based file methods that work naturally with async/await and try/catch.
  • Default behavior overwrites: writeFile() creates the file if it does not exist or replaces its existing contents if it already does.
  • Appending instead of overwriting: Pass { encoding: "utf8", flag: "a" } (or use appendFile) when adding lines to an existing log file.

2. Writing Formatted JSON Data (JSON.stringify)

Convert JavaScript objects or arrays into a JSON string with JSON.stringify(payload, null, 2) and ensure parent directories exist with mkdir(..., { recursive: true }):

// Serialize and write JSON data to a file, creating parent folders if needed
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";

async function saveJsonFile(filePath, data) {
  const folderPath = path.dirname(filePath);
  await mkdir(folderPath, { recursive: true });

  const jsonText = `${JSON.stringify(data, null, 2)}\n`;
  await writeFile(filePath, jsonText, "utf8");
  console.log("Saved JSON file:", filePath);
}

const reportData = {
  generatedAt: new Date().toISOString(),
  itemsProcessed: 42,
  ok: true
};

saveJsonFile("./data/report.json", reportData).catch((err) => {
  console.error("Failed to write JSON file:", err);
});
  • JSON.stringify(data, null, 2): Pretty-prints JSON with 2-space indentation so config or data files are easy to read and diff.
  • mkdir(path.dirname(filePath), { recursive: true }): Prevents ENOENT errors when writing into a nested directory that does not exist yet.

3. Common Traps to Avoid

Writing files in Node.js trips up developers when paths, async flow, or data types are overlooked:

  • Passing a raw object directly to writeFile() without JSON.stringify(): Objects coerce to "[object Object]" or get rejected—always serialize structured data with JSON.stringify() first.
  • Using writeFileSync() inside request handlers or hot paths: Synchronous fs methods block the Node.js event loop until disk I/O finishes, hurting throughput in servers and concurrent tasks.
  • Ignoring missing parent directories (ENOENT) or unhandled rejections: Always create missing directories (mkdir with recursive: true) and handle errors with try/catch or .catch().

TL;DR: Use await writeFile(filePath, text, "utf8") from node:fs/promises for text, and pair JSON.stringify(data, null, 2) with mkdir(..., { recursive: true }) when writing JSON files.

Are you writing config/state JSON files, appending logs, or saving data inside an Express/HTTP server handler?