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):
fs.stat()resolves the symbolic link. If the path you pass to it is a symlink, Node.js will follow the link to the actual target file or directory and return the metadata for that target.fs.lstat()does not resolve symbolic links. If the path you pass to it is a symlink, Node.js will return the metadata for the symbolic link itself, rather than the file it points to.
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:
isSymbolicLink()Method: Thestatsobject has a helper method calledisSymbolicLink(). When usingfs.stat(), this will always returnfalsebecause the method resolves to the target file. It will only returntruewhen you usefs.lstat()on a symlink.- 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
- Use
fs.stat()when you only care about the actual content of the files. For example, if you want to read a file, check its actual size, or see when the target content was last modified. - Use
fs.lstat()when you are writing file system utilities, such as a custom directory walker, a backup tool, or a file deletion script. In these cases, you need to know if a file is a link so you can handle it appropriately without accidentally modifying or deleting the target resource.