Node.js

Write a small JSON file in Node.js

Serialize a value with JSON.stringify and write it using UTF-8. Add a final newline for a file that is easy to inspect with text tools, and read it back when checking the result.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import * as fs from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
const directory = await fs.mkdtemp(join(tmpdir(), "file-guide-"));
try {
  const path = join(directory, "settings.json");
  const settings = {theme: "dark", retries: 0};
  await fs.writeFile(path, JSON.stringify(settings, null, 2) + "\n", "utf8");
  const saved = JSON.parse(await fs.readFile(path, "utf8"));
  console.log(saved.theme, saved.retries);
} finally {
  await fs.rm(directory, {recursive: true, force: true});
}

How it works

The indentation argument creates a readable representation; it does not change the JSON data. Awaiting writeFile reports completion or failure before the read begins. The temporary example avoids overwriting any existing user configuration.

Limits and mistakes

WriteFile normally replaces existing contents and is not a complete atomic-update or durability protocol. Concurrent writers need coordination. JSON also cannot represent every JavaScript type, so validate the data schema before serializing.

Check the result

Expect dark 0. Check the actual serialized file during adaptation and confirm the newline and encoding. Test malformed input separately from filesystem failures.

Sources

Reference documentation for the behavior used in this guide: