Node.js fsPromises.lstat() Method
Last Updated :
18 Feb, 2023
The fs.promises.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 computers. The lstat() method gives some information specific to files and folders using methods defines on stats objects (data provided by lstat). The fs.promises.lstat() method returns a resolved or rejected promise and hence avoids the callback nesting or callback hell problems that may occur in fs.readdir() method.
Syntax
fs.promises.lstat(path, options)
Parameter: This method accepts two parameters as mentioned above and described below:
path: It is a 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() method then it is bigint or not(default-false).
Return Value: It returns a resolved or rejected promise. The promise is resolved with stats object if the directory is successfully read otherwise rejected with an error object if any error is occurred (example-specified directory not exist or does not have permissions to read files, etc).
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 specified below.
- stats.isDirectory(): Returns true if stats object describes a file system directory.
- stats.isFile(): Returns true if stats object describes a regular file.
- stats.isSocket(): Returns true if stats object describes a socket.
- stats.isSymbolicLink(): Returns true if stats object describes a symbolic link.
- stats.isFile(): Returns true if stats object describes a regular file.
- stats.isFIFO(): Returns true if stats object describes first in first out pipe.
- stats.size: Specifies the size of the file in bytes.
- stats.blocks: Specifies the number of blocks allocated for the file.
Example 1:
javascript
const fs = require( 'fs' )
fs.readdir(process.cwd(), (err, filenames) => {
if (err) {
console.log(err)
return
}
for (let filename of filenames) {
fs.promises.lstat(filename)
.then(stats => {
if (stats.isFile()) {
console.log(`${filename} ---------> File`)
} else {
console.log(`${filename} ---------> Folder`)
}
})
. catch (err => {
console.log(err)
})
}
})
|
Output:
Example 2:
javascript
const fs = require( 'fs' )
fs.readdir(process.cwd(), async (err, filenames) => {
if (err) {
console.log(err)
return
}
for (let filename of filenames) {
fs.promises.lstat(filename)
.then(stats => {
console.log(
`${filename} --------> ${stats.size} bytes`)
})
. catch (err => {
console.log(err)
})
}
})
|
Output:
Reference: https://nodejs.org/api/fs.html#fs_fspromises_lstat_path_options
Share your thoughts in the comments
Please Login to comment...