Node.js - fs.stat


Node.js provides set of useful functions to get information of system files. The most basic one is 
fs.stat

Function Call


The arguments in turn are:
  • path: the path to the file.
  • options: object of function options. This argument can be omitted.
  • callback: function being called after the stat function.
For example, lets take this code:

The result comparing to property viewer in windows OS will look like this:


fs.stat vs fs.lstat

Another function which serve similar purposes as fs.stat is fs.lstat. They all give user information of systems file, however they are used in different cases:
  • fs.stat: if the path is a symbolic link, the function returns information of the target file.
  • fs.lstat: if the path is a symbolic link, the function returns information of the symlink, not the target file.

Notice When Using fs.stat

The function's purpose is to get all detail info of a file, therefore it would take a quite operations when processing. Considering using other functions as stated in the official document:
"Using fs.stat() to check for the existence of a file before calling fs.open()fs.readFile() or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, fs.access() is recommended."

Related Links 

Comments

Popular Posts