Back to results for “Advanced Node.js”
Node.js › File System & File Processing

What is the difference between fs.stat() and fs.lstat(), and when does the distinction matter?

Intermediate

Answer

fs.stat() returns file information, automatically following symbolic links to report on the actual target file they point to. fs.lstat() returns information about the symbolic link itself (its size, type) rather than the file it points to -- the distinction matters specifically when working with symlinks and you need to know whether a given path is itself a symlink, rather than transparently resolving through it to whatever it points to.
const fs = require('node:fs/promises');

const stats = await fs.lstat('shortcut.txt');
if (stats.isSymbolicLink()) {
  const target = await fs.readlink('shortcut.txt');
  console.log('This is a symlink pointing to:', target);
}
Real-world example A file-organization tool that needs to detect and specifically handle symbolic links (rather than silently following them, which could create infinite loops with circular symlinks) uses fs.lstat() to identify symlinks before deciding how to process them.

Common follow-ups: What specific problem, like an infinite loop, could occur if a file-tree-walking tool doesn't account for symbolic links at all?;What information does fs.Stats provide beyond just file size and type, like timestamps?