fs.stat Reads Path Metadata
Read a path's size, timestamps, and entry kind with fs.stat, distinguishing files from directories before acting on the metadata.
Code
import { writeFile, mkdir, stat } from 'node:fs/promises';
await writeFile('notes.txt', 'hello world');
await mkdir('archive');
const file = await stat('notes.txt');
const dir = await stat('archive');
console.log('file size:', file.size, 'isFile:', file.isFile());
console.log('dir isDirectory:', dir.isDirectory());
console.log('file mtime is a Date:', file.mtime instanceof Date);
console.log('file mtimeMs > 0:', file.mtimeMs > 0);
console.log('size matches content:', file.size === Buffer.byteLength('hello world'));
console.log('relative path resolves to same file:', (await stat('./notes.txt')).isFile());Output
Captured from a sandboxed run of this snippet in the build pipeline.
file size: 11 isFile: true
dir isDirectory: true
file mtime is a Date: true
file mtimeMs > 0: true
size matches content: true
relative path resolves to same file: trueInside the snippet
Every asynchronous step is awaited, so rejections surface where the call happens. node:fs/promises supplies writeFile, mkdir, stat — built-in surface, no package involved.
Demo state sits in top-level bindings: file, dir.
What to watch for
node:fs/promisesis a Node.js built-in module — it ships with the runtime, so there is nothing to install.
Putting it to use
The run emits 6 labeled sections — file size:, dir isDirectory:, file mtime is a Date:, file mtimeMs > 0:, size matches content:, relative path resolves to same file: — one per step.
Core lines
await writeFile('notes.txt', 'hello world');
const file = await stat('notes.txt');
const dir = await stat('archive');
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SVG Path VisualizerParse SVG path d attributes (M/L/H/V/C/S/Q/T/A/Z), render a scaled wireframe preview with vertices and control handles, and compute bounding boxes.
FAQ
- Is the imported module an npm package?
- No — `node:fs/promises` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.
Report a problem with this exampleOpens a pre-filled issue on GitHub.