Reading and writing files with fs/promises
- Version
- 24
- Since
- 10.0.0
- Review
- Draft
Summary#
Use node:fs/promises to await asynchronous filesystem operations. readFile reads an entire file. writeFile creates the destination or replaces its contents by default.
Syntax#
import { readFile, writeFile } from "node:fs/promises";
await writeFile(path, text, "utf8");
const contents = await readFile(path, "utf8");
Pass "utf8" to readFile to get a string. With no encoding, it returns a Buffer.
Example#
Save as shift.mjs and run node shift.mjs. The script writes and reads one file in a fresh temporary directory and removes the directory in finally.
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const directory = await mkdtemp(join(tmpdir(), "dlr-nodejs-fs-"));
try {
const file = join(directory, "shift.txt");
await writeFile(file, "morning", "utf8");
const shift = await readFile(file, "utf8");
console.log(`shift=${shift}`);
} finally {
await rm(directory, { recursive: true, force: true });
}
Expected output#
shift=morning
Common mistakes#
Await the write before reading or writing the same file again. Starting a second write to the same path before the first settles is unsafe. Use streams for large inputs when you need to process data a chunk at a time.
Version applicability#
Node.js 10.0.0 introduced the filesystem promises API. The standalone fs/promises module arrived in 14.0.0. The example needs 14.14.0 or later for rm. It also uses top-level await and node: imports, available in the 14.x line from 14.8.0 and 14.13.1, respectively.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0