statreturns information about the file or directory that the given path points to, following any symbolic links.lstatreturns information about the symbolic link itself, not the target file or directory it points to. It doesn’t follow the symlink, providing details about the symlink itself.
fs.stat vs. fs.statSync in Node.js
Key takeaways:
fs.stat()is asynchronous, meaning it fetches directory statistics while other code continues to run.fs.statSync()is synchronous, meaning it blocks the code execution until the statistics are fetched.Use
fs.stat()for non-blocking operations, where other tasks can run simultaneously.Use
fs.statSync()when the directory stats must be fetched immediately, blocking further code execution.Both methods return the same type of information but are used in different situations based on whether you need to block or allow concurrent code execution.
The fs module is a built-in file system module in Node.js that consists of several methods that can be used to access and manipulate files on the operating system. stat() and statSync() are the fs methods used to fetch the static information of a directory.
Difference between stat() and statSync()
The main difference between both methods is that stat() function is an asynchronous method and statSync() is a synchronous method.
Let's look at their key differences and get a basic idea regarding when to use which method.
stat() vs. statSync()
stat() | statSync() | |
Asynchronous vs. Synchronous | It is asynchronous, which means when this function is called, it will execute and fetch the statistics of the given directory while the other code continues to execute. | It is synchronous, which means when this function is called, it will execute and fetch the statistics of the given directory and send a callback. Till then the system will go in waiting and nothing else is executed. |
Syntax | Use if-else to handle cases. | Use try-catch to handle cases. |
When to Use | Used when there is a need to handle non-blocking requests. Hence, no immediate need to fetch the statics. | Used where there is a need for a blocking request to ensure immedate fetching of directory statistics . |
Real Life Example | We can fetch information asynchronously in a file manager application, allowing the information to be fetched while the user interface is available for other operations. | We can fetch information synchronously when an action is to be performed on the directory corresponding to the retreived statistics. |
Required import
Import the Node.js package fs to access files:
const fs = require('fs')
Syntax
The parameters for the fs.stat() and fs.statSync() methods are the same, with a slight difference in syntax.
The syntax for fs.stat() when handling its cases using if-else conditions:
const fs = require('fs');fs.stat('path/to/directoryName', (err, stats) => {if (err) {console.error(err);return;}console.log(stats);});
The syntax for fs.statSync() when handling its cases using try-catch block:
const fs = require('fs');try {const stats = fs.statSync('path/to/directoryName');console.log(stats);} catch (err) {console.error(err);}
Parameters
path: The destination of the directory for which the information is to be fetched.directoryName: The name of the directory for which the information is to be fetched.stats: A variable in which the fetched information of the directory is saved.err: A callback function that is called once the method is executed and returns one of the two cases:error: The method fails to fetch information for the specified directory.null: The method successfully fetches the information for the specified directory.
Code example
This code fetches statistical information for the specified directory and saves it in a stats variable. We use both methods to communicate the difference between their implementations. Moreover, we have used a direct directory and a nested directory with a path to show how they are reached.
Output explanation
Let’s understand the output of the above example code and examine the difference in the behavior of a synchronous and asynchronous function.
Message 1is printed because it is the first statement in the code.Message 2is printed, which is the very next statement after thestat()method is called.nestedDirdirectory’s statistic information is fetched throughstatSync()method, and itsmode,size, andbirthtimeare immediately displayed because synchronous commands do not allow the code to proceed until its callback is received.Message 3is printed as it is the very next statement after thestatSync()method is called.publicdirectory’s statistic information is fetched through thestat()method, and itsmode,size, andbirthtimeare displayed once all the other code is executed.
Test your understanding
A quick quiz to test your understanding.
What will happen if we directly print stats?
console.log(stats);
It will show all the statistical information of the given file or directory.
It will throw an error.
Conclusion
In conclusion, both fs.stat() and fs.statSync() are used to retrieve directory statistics in Node.js, but they differ in their execution behavior. fs.stat() is asynchronous, allowing other tasks to continue while fetching stats, making it suitable for non-blocking operations. On the other hand, fs.statSync() is synchronous and blocks further execution until the statistics are fetched, making it useful when immediate access to the stats is required. Choosing between these methods depends on whether your application needs to prioritize non-blocking tasks or requires immediate results for further operations.
Unlock your full potential with our comprehensive Node.js course. Dive deeper into the topic and gain hands-on experience through expert-led lessons:
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What is the difference between stat and Lstat in node JS?
When to use fstat vs stat?
What is the difference between fstat and Lstat functions?
Free Resources