Node.js fs.Dir.read() Method
Last Updated :
06 Apr, 2023
The fs.Dir.read() method is an inbuilt application programming interface of class fs.Dir within File System module which is used to read each next directory (dirent) one by one asynchronously.
Syntax:
const fs.Dir.read(callback)
Parameter: This method takes a callback function as a parameter that has the following arguments.
- err: if any error occurred.
- dirent: dirent of the directory after reading.
Return Value: This method does not return any value.
Example 1: The below program illustrates the use of fs.Dir.read() method in Node.js
Filename: GFG.js
Javascript
const fs = require( 'fs' );
async function stop(path) {
const dir = await fs.promises
.opendir( new URL('file:
for (let i = 1; i <= 2; i++) {
dir.read((err, dirent) => {
console.log(`${dirent.name}
${err ? 'does not exist ' : ' exists '}`);
});
}
}
// Catching error
stop(' ./'). catch (console.error);
|
Run the GFG.js file using the following command:
node GFG.js
Output:
Example 2: The below program illustrates the use of fs.Dir.read() method in Node.js
Filename: GFG.js
Javascript
const fs = require( 'fs' );
async function stop(path) {
const dir = await fs.promises.opendir(path);
for (let i = 1; i <= 4; i++) {
dir.read((err, dirent) => {
if (err) throw err
console.log(dirent.name);
});
}
}
stop('./'). catch (console.error);
|
Run the GFG.js file using the following command:
node GFG.js
Output:
Note: The above program will not run on online JavaScript and script editor.
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_dir_read_callback
Share your thoughts in the comments
Please Login to comment...