Skip to content
Related Articles

Related Articles

How to operate callback-based fs.readdir() method with promises in Node.js ?
  • Last Updated : 18 Jul, 2020

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




// 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} `);
})

Implementing the same functionality using async-await :




// 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}`);
})

Run the index.js file using the following command:

node index.js

Output:

Example 2: Filename: index.js




// 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)
})

Implementing the same functionality using async-await :




// 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}`);
})

Run the index.js file using the following command:

node index.js

Output:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :