Dev Helpers

Node.js / File operations

Read file metadata

Dev Helpers · June 26, 2025

File metadata describes the path at the time it was inspected. A later read can still fail if the file changes.

Worked example

import * as fs from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const dir = await fs.mkdtemp(join(tmpdir(), "helpers-"));
const file = join(dir, "note.txt");
await fs.writeFile(file, "build");
try {
  console.log((await fs.stat(file)).size);
} finally {
  await fs.rm(dir, { recursive: true, force: true });
}

Result

5

Implementation notes

A metadata check followed by a separate operation can race with a file move. Handle failure where the operation is actually attempted.

Try it yourself

Compare a directory entry and a regular file before attempting to read either.

Open the Node.js example →

Editorial date June 26, 2025 · Published December 6, 2026

Related articles

Safely parse malformed input

Parsing user-provided JSON needs a failure path. Successful parsing alone does not establish that the result has the expected shape.

Checksum bytes with CRC32

CRC32 is useful for detecting accidental changes to a byte sequence. Record the input encoding so different producers compute the same checksum.

Attach details to a mark

Performance marks can carry details about the operation they describe. Small stable identifiers are easier to aggregate than large payloads.