Node.js
Inspect a file’s size and type
Use stat to inspect metadata such as byte size and whether a path refers to a regular file. A text file’s size is measured in bytes, not JavaScript characters.
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, "text.txt");
await fs.writeFile(path, "é", "utf8");
const info = await fs.stat(path);
console.log(info.isFile(), info.size);
} finally {
await fs.rm(directory, {recursive: true, force: true});
}How it works
The sample character uses two UTF-8 bytes even though it is one visible letter. Stat reports the filesystem’s byte count. This distinction matters when enforcing upload limits or estimating how much data a read operation will consume.
Limits and mistakes
Stat follows symbolic links; lstat inspects the link itself. Metadata is a snapshot and may change before a later operation. Do not use a successful stat as proof that a subsequent read or write cannot fail.
Check the result
Expect true 2. Compare the metadata with Buffer.byteLength of the intended text, and test a directory path to avoid treating every successful stat as a regular file.
Sources
Reference documentation for the behavior used in this guide: