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

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Program to read file and folders of 
// the current working 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)
  
// Reading current working directory
readDir(process.cwd())
// If promise resolved and datas are fetched
.then(filenames => {
  for(let filename of filenames) {
    console.log(filename)
  }
})
  
// If promise is rejected
.catch(err => {
   console.log(`Error occurs, 
   Error code -> ${err.code},
   Error No -> ${err.errno} `);
})

chevron_right


Implementing the same functionality using async-await :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Program to read file and folders of the
// current working 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 readDirectory = async (path) => {
  const filenames = await readDir(path)
  for(let filename of filenames){
    console.log(filename)
  }
}
  
readDirectory(process.cwd())
// If promise is rejected
.catch(err => {
   console.log(`Error occurs, 
   Error code -> ${err.code},
   Error No -> ${err.errno}`);
})

chevron_right


Run the index.js file using the following command:

node index.js

Output:

Example 2: Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Program to read file and folders of the
// current working directory or as the path
// given by command line argument
   
// 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)
  
// The process.cwd() gives current working directory
const targetDir = process.argv[2] || process.cwd()
   
readDir(targetDir)
   
// If promise resolved and datas are fetched
.then(filenames => {
  for(let filename of filenames) {
    console.log(filename)
  }
})
  
// If promise is rejected
.catch(err => {
  console.log(err)
})

chevron_right


Implementing the same functionality using async-await :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Program to read file and folders of the 
// current working directory or as the path
// given by command line argument
   
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// The process.cwd() gives current working directory
const targetDir = process.argv[2] || process.cwd()
  
// Convert callback based methods to promise
// based methods
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)
// If promise is rejected
.catch(err => {
   console.log(`Error occurs, 
   Error code -> ${err.code},
   Error No -> ${err.errno}`);
})

chevron_right


Run the index.js file using the following command:

node index.js

Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.