Open In App

How to operate callback-based fs.lstat() method with promises in Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

The fs.lstat() method is defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The lstat() method gives some information specific to files and folders using methods define on stats objects (data provided by lstat).
The fs.lstat() method is based on callback. Using callback methods lead to a great chance of callback nesting or callback hell problems. Thus to avoid it, we almost always like to work with a promise-based method. Using some extra node.js methods we can operate a callback-based method in promise way.
Syntax: 
 

fs.lstat(path, options)

Note: Callback not required since we operate the method with promises.
Parameter: This method accept two parameters as mentioned above and described below: 
 

  • path: It is an string, buffer or url that specifies the path to the directory, whose contents we try to read.
  • options: It is an optional parameter. One options parameter is ‘bigint’, it is a boolean value. Here we specify if the numeric value in returned stats object by fs.lstat() is bigint or not(default-false).

Return Value: If method operates with promises, it returns a resolved or rejected promise. Promise is resolved with stats object if the directory is successfully read otherwise rejected with an error object if any error occurs(example-specified directory not exist or does not have permissions to read files, etc).
The stats object returned from the resolved promise has some properties and methods defined in it which helps in getting some specific details about the target files or folders. Some of the methods are specifies below.
 

  • stats.isDirectory(): It returns true if stats object describes a file system directory.
  • stats.isFile(): It returns true if stats object describes a regular file.
  • stats.isSocket(): It returns true if stats object describes a socket.
  • stats.isSymbolicLink(): It returns true if stats object describes a symbolic link.
  • stats.isFile(): It returns true if stats object describes a regular file.
  • stats.isFIFO(): It returns true if stats object describes first in first out pipe.
  • stats.size: It specifies the size of the file in bytes.
  • stats.blocks: It specifies the number of blocks allocated for the file.

Example 1: Filename: index.js 
 

javascript




// Program to identify files and folders
// of a directory
 
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
 
// Convert callback based methods to
// promise based methods
const readDir = util.promisify(fs.readdir)
const lStat = util.promisify(fs.lstat)
 
 
const fileOrFolder = async (path) => {
    const filenames = await readDir(path)
 
    for (let filename of filenames) {
 
        // Calling lstat method to give the
        // stats object for every directory
        const stats = await lStat(filename)
 
        // Check file or folder
        if (stats.isFile()) {
            console.log(
            `${filename} ---------> File`)
        } else {
            console.log(
            `${filename} ---------> Folder`)
        }
    }
}
 
// Driver code
// The process.cwd() gives current
// working directory
fileOrFolder(process.cwd())
 
    // If promise is rejected
    .catch(err => {
        console.log(`Error occurs,
        Error code -> ${err.code},
        Error No -> ${err.errno} `);
    });


Run index.js file using the following command: 
 

node index.js

Output: 
 

Example 2: Filename: index.js 
 

javascript




// Program to count the size of
// directories in bytes
 
// Importing File System and
// Utilities module
const fs = require('fs')
const util = require('util')
 
// Convert callback based methods to
// promise based methods
const readDir = util.promisify(fs.readdir)
const lStat = util.promisify(fs.lstat)
 
const sizeOfDirectories = async (path) => {
    const filenames = await readDir(path)
    for (let filename of filenames) {
 
        // Calling lstat method to give the
        // stats object for every directory
        const stats = await lStat(filename)
 
        // Print size of each directory
        console.log(`${filename}
          --------> ${stats.size} bytes`)
    }
}
 
// Driver code
// The process.cwd() gives current
// working directory
sizeOfDirectories(process.cwd())
    // If promise is rejected
    .catch(err => {
        console.log(`Error occurs,
        Error code -> ${err.code},
        Error No -> ${err.errno}`);
    })


Run index.js file using the following command: 
 

node index.js

Output: 
 

 



Last Updated : 12 Jul, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads