Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to operate callback-based fs.opendir() method with promises in Node.js ?
Next article icon

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

Last Updated : 18 Jul, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

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:



Next Article
How to operate callback-based fs.opendir() method with promises in Node.js ?
author
hunter__js
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • Node.js-fs-module
  • Node.js-Misc

Similar Reads

  • How to operate callback-based fs.readFile() method with promises in Node.js ?
    The fs.readFile() 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 readFile() method is used to asynchronously read the entire contents of a file and returns the buffer form of the data. The fs.read
    5 min read
  • How to operate callback-based fs.rename() method with promises in Node.js ?
    The fs.rename() method is defined in the File System module of Node.js. The File System module is basically to interact with hard-disk of the user’s computer. The rename() method is used to rename the file at the given old path to a given new path. If the new path file already exists, it will be ove
    5 min read
  • How to operate callback-based fs.mkdir() method with promises in Node.js ?
    The fs.mkdir() 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 mkdir() method is used to asynchronously create a directory. The fs.mkdir() method is based on callback. Using callback methods leads
    4 min read
  • How to operate callback-based fs.truncate() method with promises in Node.js ?
    The fs.truncate() method 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 truncate() method is used to modify the inner contents of the file by ‘len’ bytes. If len is shorter than the file’s current length, t
    4 min read
  • How to operate callback-based fs.opendir() method with promises in Node.js ?
    The fs.opendir() 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 method used to asynchronously open a directory.The fs.opendir() method is based on callback. Using callback methods leads to a great
    5 min read
  • How to operate callback based fs.writeFile() method with promises in Node.js ?
    The fs.writeFile() is a method 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 fs.writeFile() method asynchronously writes data to a file, replacing the file if it already exists. The fs.writeFile() method i
    5 min read
  • How to operate callback based fs.appendFile() method with promises in Node.js ?
    The fs.appendFile() 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 appendFile() method is used to append new data in the existing file or if the file does not exist then the file is created first
    4 min read
  • How to convert function call with two callbacks promise in Node.js ?
    Promise: Promise is used to handle the result, if it gets the required output then it executes the code of then block, and if it gets the error then it executes the code of the catch block. A promise looks like this - function() .then(data => { // After promise is fulfilled console.log(data); })
    3 min read
  • Node.js fs.promise.readdir() Method
    The fs.promise.readdir() method defined in the File System module of Node.js. The file System module is basically to interact with the hard disk of the users computer. The readdir() method is used to read the files and folders names. The fs.promise.readdir() method returns a resolved or rejected pro
    2 min read
  • How to Convert an Existing Callback to a Promise in Node.js ?
    Node.js, by nature, uses an asynchronous, non-blocking I/O model, which often involves the use of callbacks. While callbacks are effective, they can lead to complex and hard-to-read code, especially in cases of nested callbacks, commonly known as "callback hell." Promises provide a cleaner, more rea
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences