The fs.readdir() 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 readdir() method is used to read the contents of a directory.
The fs.readdir() method is based on callback. Using callback methods leads 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.readdir(path, options)
Note: Callback not required since we operate the method with promises.
Parameters: 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, here we specify encoding techniques(default-utf8) etc.
Approach: The fs.readdir() method based on callback. To operate it with promises, first, we use promisify() method defined in the utilities module to convert it into a promise based method.
Example 1: Filename: index.js
const fs = require( 'fs' )
const util = require( 'util' )
const readDir = util.promisify(fs.readdir)
readDir(process.cwd())
.then(filenames => {
for (let filename of filenames) {
console.log(filename)
}
})
. catch (err => {
console.log(`Error occurs,
Error code -> ${err.code},
Error No -> ${err.errno} `);
})
|
Implementing the same functionality using async-await :
const fs = require( 'fs' )
const util = require( 'util' )
const readDir = util.promisify(fs.readdir)
const readDirectory = async (path) => {
const filenames = await readDir(path)
for (let filename of filenames){
console.log(filename)
}
}
readDirectory(process.cwd())
. catch (err => {
console.log(`Error occurs,
Error code -> ${err.code},
Error No -> ${err.errno}`);
})
|
Run the index.js file using the following command:
node index.js
Output:

Example 2: Filename: index.js
const fs = require( 'fs' )
const util = require( 'util' )
const readDir = util.promisify(fs.readdir)
const targetDir = process.argv[2] || process.cwd()
readDir(targetDir)
.then(filenames => {
for (let filename of filenames) {
console.log(filename)
}
})
. catch (err => {
console.log(err)
})
|
Implementing the same functionality using async-await :
const fs = require( 'fs' )
const util = require( 'util' )
const targetDir = process.argv[2] || process.cwd()
const readDir = util.promisify(fs.readdir)
const readDirectory = async (path) => {
const filenames = await readDir(path)
for (let filename of filenames){
console.log(filename)
}
}
readDirectory(targetDir)
. catch (err => {
console.log(`Error occurs,
Error code -> ${err.code},
Error No -> ${err.errno}`);
})
|
Run the index.js file using the following command:
node index.js
Output:
