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.

JavascriptCli Tooling

Code

javascriptsnippet
14 lines
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: true

Inside 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/promises is 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

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.