How to operate callback-based fs.opendir() method with promises in Node.js ?
Last Updated :
24 Nov, 2021
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 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. The promise is resolved with ‘fs.Dir’ object, the object itself contains other functions for accessing and closing the directory. In case if the promise is rejected it will be rejected with an error object.
Syntax:Â
fs.opendir(path, options)
Note : Callback not required since we operate the method with promises.
Parameters: Accepts two parameter path and options as mentioned above. The options is an optional parameter. Â
- path: It is an String, Buffer or Url that specifies the path to the directory that has to be open.
- options: It is an optional parameter which affects the output in someway accordingly provide it to the function call or not.Â
- encoding: It specifies the encoding technique, default is ‘UTF8’
- bufferSize: It is a number that specifies the number of directory entries that are buffered internally when reading from the directory. High value of bufferSize, ensures good performance but leads to more memory usages.
Returns: If method operates with promises it returns a promise resolved with 'fs.Dir' object, the object itself contains other functions for accessing and closing the directory. In case if the promise is rejected it will be rejected with an error object.
'dir' object methods:Â
- dir.close(): It asynchronously close the resources of the directory and hence Subsequent attempt to read will result in errors. A Promise is returned that will be resolved after the resource has been closed.
- dir.closeSync(): It synchronously close the resources of the directory and hence Subsequent attempt to read will result in errors.
- dir.path: Returns the path to the directory.
- dir.read(): It asynchronously read the next directory entry. After the read is completed, a Promise is returned that will be resolved with an fs.Dirent, or null if there are no more directory read.
Approach: fs.opendir() 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Â
javascript
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods
// to promise based methods
const openDir = util.promisify(fs.opendir)
openDir('./testDirectory')
.then(dir => {
console.log('Directory is opened')
// Path to the directory
console.log(`Path to the directory:
${dir.path}`)
// Closing directory
return dir.close()
})
.then(() => {
console.log('Directory closed')
console.log('\nFurther attempt to'
+ ' read sub-directories:\n')
// Further attempt to access the
// directory results in error
return dir.read()
})
.then(dirent => {
// Does not execute since directory
// is closed catch block runs instead
console.log(dirent)
})
.catch(err => {
console.log('Error, Something went wrong!')
})
Implementing the same functionality using async-await.Â
javascript
// Importing File System and
// Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods
// to promise based methods
const openDir = util.promisify(fs.opendir)
const fetchDirectory = async (path) => {
// Opeaning directory
const dir = await openDir(path)
console.log('Directory is opened')
// Path to the directory
console.log(`Path to the directory: ${dir.path}`)
// Closing directory
await dir.close()
console.log('Directory closed')
console.log('\nFurther attempt to '
+ 'read sub-directories:\n')
// Further attempt to access the directory
// results in error does not execute since
// directory is closed catch block runs
// instead
const subDir = await dir.read()
console.log(subDir)
}
fetchDirectoey('./testDirectory')
.catch(err => {
console.log('Error, Something went wrong!')
})
Run index.js file using the following command:Â
Â
node index.js
Output:Â
Â
Directory is opened
Path to the directory: testDirectory
Directory closed
Further attempt to read sub-directories:
Error, Something went wrong!
Example 2: Filename index.jsÂ
Â
javascript
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods to
// promise based methods
const openDir = util.promisify(fs.opendir)
openDir('./testDirectory')
.then(dir => {
console.log('Directory is opened')
// Path to the directory
console.log(`Path to the directory: ${dir.path}`)
// Reading sub-directories or files
console.log('\nReading sub-directories:\n')
return dir.read()
})
.then(dirent => {
console.log(`Sub-Directory : ${dirent.name}`)
// Reading further sub directories
return dir.read()
})
.then(dirent => {
console.log(`Sub-Directory : ${dirent.name}`)
return dir.read()
})
.then(dirent => {
console.log(`Sub-Directory : ${dirent.name}`)
return dir.read()
})
.then(dirent => {
console.log(`Sub-Directory : ${dirent.name}`)
return dir.read()
})
.then(dirent => {
console.log(`Sub-Directory : ${dirent.name}`)
return dir.read()
})
.catch(err => {
console.log('Error, Something went wrong!')
})
Implementing the same functionality using async-await.Â
Â
javascript
// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
// Convert callback based methods
// to promise based methods
const openDir = util.promisify(fs.opendir)
const fetchDirectory = async (path) => {
// Opeaning directory
const dir = await openDir(path)
console.log('Directory is opened')
// Path to the directory
console.log(`Path to the directory: ${dir.path}`)
// Reading sub-directories or files
console.log('\nReading sub-directories:\n')
const subDir1 = await dir.read()
const subDir2 = await dir.read()
const subDir3 = await dir.read()
const subDir4 = await dir.read()
const subDir5 = await dir.read()
// Printing
console.log(`Sub-Directory : ${subDir1.name}`)
console.log(`Sub-Directory : ${subDir2.name}`)
console.log(`Sub-Directory : ${subDir3.name}`)
console.log(`Sub-Directory : ${subDir4.name}`)
console.log(`Sub-Directory : ${subDir5.name}`)
}
fetchDirectory('./testDirectory')
.catch(err => {
console.log('Error, Something went wrong!')
})
Run index.js file using the following command:Â
Â
node index.js
Output:Â
Â
Directory is opened
Path to the directory: testDirectory
Reading sub-directories:
Sub-Directory : testFile1.txt
Sub-Directory : testFile2.txt
Sub-Directory : teasrFile3.txt
Sub-Directory : testFile4.txt
Sub-Directory : null
Â
Similar Reads
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.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.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 l
3 min read
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.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.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.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); }) .c
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
How to export promises from one module to another module node.js ?
JavaScript is an asynchronous single-threaded programming language. Asynchronous means multiple processes are handled at the same time. Callback functions vary for the asynchronous nature of the JavaScript language. A callback is a function that is called when a task is completed, thus helps in prev
1 min read