Node.js

Read a UTF-8 text file in Node.js

Read a small text file with the promise-based readFile API and an explicit UTF-8 encoding. The resolved result is a string rather than a Buffer when an encoding is supplied.

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, "note.txt");
  await fs.writeFile(path, "Hello from a file\n", "utf8");
  const text = await fs.readFile(path, "utf8");
  console.log(text.trimEnd());
} finally {
  await fs.rm(directory, {recursive: true, force: true});
}

How it works

This self-contained example creates a temporary directory, writes a fixture, reads it, and removes only that temporary directory in finally. Awaiting each operation ensures the file exists before reading. Explicit encoding makes subsequent string operations unambiguous.

Limits and mistakes

ReadFile loads the complete contents into memory. Use streaming for large inputs and handle read errors such as a missing path or permission failure. Specifying UTF-8 does not prove that the original file was encoded correctly.

Check the result

Expect Hello from a file. Replace the fixture with a non-ASCII character to verify decoding, and use a nonexistent path in a separate test to exercise your error handling.

Sources

Reference documentation for the behavior used in this guide: