Difference Between fs.stat and fs.lstat in Node.js

When working with the file system in Node.js, the fs module provides several methods to retrieve file metadata. Two of the most commonly confused methods are fs.stat() and fs.lstat(). This article explains the key difference between these two functions, specifically how they handle symbolic links (symlinks), and provides practical code examples to help you choose the right one for your Node.js scripts.

The Core Difference

The fundamental difference between fs.stat() and fs.lstat() lies in how they handle symbolic links (symlinks):

If the path you are analyzing is a regular file or directory (and not a symbolic link), both fs.stat() and fs.lstat() will return the exact same metadata.

Code Example Comparison

To see this difference in action, consider a scenario where you have a real file named target.txt and a symbolic link named link.txt pointing to it.

const fs = require('fs');

// 1. Using fs.stat on a symbolic link
fs.stat('link.txt', (err, stats) => {
  if (err) throw err;
  console.log('fs.stat - Is symbolic link?:', stats.isSymbolicLink()); // Output: false
  console.log('fs.stat - File size:', stats.size); // Output: Size of target.txt
});

// 2. Using fs.lstat on a symbolic link
fs.lstat('link.txt', (err, stats) => {
  if (err) throw err;
  console.log('fs.lstat - Is symbolic link?:', stats.isSymbolicLink()); // Output: true
  console.log('fs.lstat - File size:', stats.size); // Output: Size of the link path string
});

Key Observations from the Example:

  1. isSymbolicLink() Method: The stats object has a helper method called isSymbolicLink(). When using fs.stat(), this will always return false because the method resolves to the target file. It will only return true when you use fs.lstat() on a symlink.
  2. File Size: fs.stat() returns the size of the target file (target.txt). fs.lstat() returns the size of the link itself (which is typically the length of the string path pointing to the target).

When to Use Which