NodeJS the fs module

In Node.js, the fs module provides a set of functions for working with the file system. One of the functions available in this module is fs.stat(), which is used to retrieve information about a file or directory.

The fs.stat() function takes a file path as its first parameter and a callback function as its second parameter. The callback function is called with two arguments: an error object (if an error occurred) and a stats object containing the file or directory information.

Here’s an example of how to use fs.stat() in Node.js:

const fs = require('fs');

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

fs.stat(filePath, (err, stats) => {
  if (err) {
    console.error(err);
    return;
  }

  // Access the file information
  console.log('File size:', stats.size);
  console.log('Last modified:', stats.mtime);
  console.log('Is a directory?', stats.isDirectory());
  console.log('Is a file?', stats.isFile());
});

In the above example, we pass the file path 'path/to/file.txt' to fs.stat(). In the callback function, we check if an error occurred. If there’s no error, we can access various properties of the stats object to get information about the file. In this example, we print the file size, last modified timestamp, and check whether it’s a directory or a file.

The stats object provides various properties and methods to retrieve file information, such as size (file size in bytes), mtime (last modified timestamp), isDirectory() (returns true if it’s a directory), and isFile() (returns true if it’s a file).

Note that fs.stat() can also be used to retrieve information about a symbolic link by passing the path to the link itself, not the target file or directory.