fs/promises and node:path

Reading and writing files with Node's promise-based file system API, and building paths safely with the path module.

                import { readFile, writeFile } from 'node:fs/promises';
              

Purpose

node:fs/promises provides promise-based file system operations β€” reading, writing, and inspecting files β€” as the modern alternative to the older callback-based node:fs API. node:path builds and resolves file paths correctly across operating systems.

Syntax

import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { join, dirname } from 'node:path';

const configPath = join(dirname(import.meta.url), 'config.json');
const data = await readFile('config.json', 'utf-8');
await writeFile('output.json', JSON.stringify({ done: true }));
await mkdir('output', { recursive: true });

Behavior notes

  • readFile/writeFile load or write an entire file’s contents at once β€” appropriate for reasonably small files; a large file is better handled with a stream (see Streams).
  • path.join() builds a path using the correct separator for the current operating system (/ on Linux/macOS, \ on Windows) β€” string-concatenating paths by hand breaks cross-platform.
  • Every fs/promises function rejects its returned promise on failure (a missing file, a permissions error) β€” always handle that with try/catch or a .catch().
  • Without an encoding argument, readFile returns a raw Buffer, not a string β€” passing 'utf-8' (as above) decodes it to text directly.

Common mistakes

  • Concatenating path segments with a hard-coded /, breaking on Windows.
  • Forgetting an encoding argument and receiving a Buffer where a string was expected.
  • Reading a very large file entirely into memory when a stream would avoid the memory cost.

Runtime notes

Node-specific β€” none of these APIs exist in a browser, which has no direct file system access for security reasons.

Taught in these lessons

Related reference