How to Get Information of a File in NodeJs? (Size, Modification time)

NodeJS fs.stat() is a powerful method of the fs module that allows us to get detailed information about a file or directory in the file system. This method provides access to the file and directory’s metadata, including size, permissions, timestamps, and more. It is widely used for various file system operations in NodeJS applications.

In this article, we will discuss the syntax, use cases and error handling of the NodeJS fs.stat() method by giving examples, and we will also take a look at the synchronous version of this method: fs.statSync.

Syntax

The fs.stat() method has straightforward syntax. It takes two arguments: the path to the file or directory and a callback function.

fs.stat(path, (err, stats) => {
  // Handle the result or error
});
  • path (string): The path to the file or directory for which you want to retrieve information.
  • err (Error object): An error object that contains information about any errors that occurred during the operation.
  • stats (fs.Stats object): An object that contains information about the file or directory.

Usage

To use the fs.stat() method, you first need to require the fs module in your Nodejs application. Once you have it, you can use the fs.stat() method to retrieve information about a file or directory.

Here’s an example that demonstrates how to use this method:

const fs = require('fs');

const filePath = 'path/to/file.txt';

fs.stat(filePath, (error, stats) => {
  if (error) {
    console.error('An error occurred:', error);
    return;
  }

  console.log('File stats:', stats);
});

In the example above, we pass the file path as the first argument to the fs.stat() method. The second argument is a callback function that will be executed once the file’s metadata is retrieved. If an error occurs during the operation, the error parameter in the callback will contain the corresponding error object. Otherwise, the stats parameter will contain the file’s metadata.

The stats object returned by the fs.stat() method provides various properties that give you detailed information about the file or directory. Here are some commonly used properties:

  • stats.isFile(): Returns true if the path represents a regular file.
  • stats.isDirectory(): Returns true if the path represents a directory.
  • stats.size: The character size of the file in bytes.
  • stats.mode: The file’s permissions represented as a numeric value.
  • stats.birthtime (Create Time): The timestamp when the file was created.
  • stats.atime (Access Time): The timestamp when the file was last accessed.
  • stats.mtime (Modification Time): The timestamp when the file was last modified.
  • stats.ctime (Change Time): The timestamp when the file’s metadata was last changed.

These properties allow to determine the type of the path (file or directory) and obtain information about its size and timestamps. Additionally, the stats object provides more advanced properties that might be useful for specific use cases.

Error Handling

The Error object returned by fs.stat() callback function can have properties that provide further information about the encountered error. Some of the commonly used properties are:

  • code: This property represents a string identifying the type of error that occurred. It can be used to determine the specific error scenario and handle it accordingly. Common error codes include 'ENOENT' (file or directory not found), 'EACCES' (permission denied), 'EISDIR' (expected a file but found a directory), and many more.
  • errno: Similar to the code property, errno provides the numeric representation of the error. It corresponds to the error codes defined by the operating system.
  • path: This property contains the path passed to fs.stat() when the error occurred. It can be useful for debugging and providing more specific error messages.
  • syscall: In some cases, the syscall property is available and indicates the name of the system call that triggered the error.
  • stack: The stack property contains a stack trace, which shows the sequence of function calls that led to the error.

Here’s an example demonstrating the usage of these properties:

fs.stat('/path/to/file', (err, stats) => {
  if (err) {
    if (err.code === 'ENOENT') {
      console.error('File not found. Please provide a valid path.');
    } else if (err.code === 'EACCES') {
      console.error('Permission denied. You do not have sufficient access rights.');
    } else {
      console.error('An error occurred while retrieving file stats:');
      console.error('Error code:', err.code);
      console.error('Error number:', err.errno);
      console.error('Path:', err.path);
      console.error('System call:', err.syscall);
      console.error('Stack trace:', err.stack);
    }
    return;
  }
  // Process the file stats
  console.log(stats);
});

By using these error features, you can handle certain error scenarios more effectively. And you can return more meaningful errors to the user.

Synchronous Version: fs.statSync

On the other hand, fs.statSync is the synchronous version of the fs.stat method. It blocks the execution of your code until it retrieves the file or directory information. It returns a stats object directly, which allows you to use the information immediately.

const fs = require('fs');

try {
  const stats = fs.statSync('/path/to/file.txt');
  console.log('File size in bytes:', stats.size);
} catch (err) {
  console.error(err);
}

Always wrap file system operations in a try-catch block when using fs.statSync, to catch any errors to be thrown.

Use Cases

Here are some common use cases for fs.stat and fs.statSync:

  1. Checking if a file exists: You can use fs.stat or fs.statSync to determine whether a file or directory exists at a given path.
  2. Getting file information: Retrieve details like file size, type, or permissions.
  3. Monitoring file changes: You can use the stats.mtime property to track when a file was last modified and trigger actions accordingly.
  4. Directory traversal: When walking through directories, you can use fs.stat or fs.statSync to gather information about each file and directory you encounter.

Conclusion

The fs.stat and fs.statSync methods are invaluable tools when working with files and directories in Node.js. Whether you need to check file existence, gather file information, or monitor changes, these methods provide essential insights into the file system.

Remember to handle errors properly, especially when dealing with asynchronous operations. By understanding and using these methods effectively, you can build Nodejs applications that interact with the file system seamlessly.

Thank you for reading

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top