![]() |
VOOZH | about |
The fs.readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory. The options argument can be used to change the format in which the files are returned from the method.
Syntax:
fs.readdir( path, options, callback )Parameters:
This method accept three parameters as mentioned above and described below:
Below examples illustrate the fs.readdir() method in Node.js:
This example demonstrates how to use the fs.readdir() method to return filenames in a directory.
Output:
Current directory filenames:
index.js
package.json
text_file_a.txt
text_file_b.txt
Current directory files:
Dirent { name: 'index.js', [Symbol(type)]: 1 }
Dirent { name: 'package.json', [Symbol(type)]: 1 }
Dirent { name: 'text_file_a.txt', [Symbol(type)]: 1 }
Dirent { name: 'text_file_b.txt', [Symbol(type)]: 1 }Here’s an example where the withFileTypes option is set to true, and the results are returned as fs.Dirent objects.
Output:
Filenames with the .txt extension:
text_file_a.txt
text_file_b.txtWhen using fs.readdir(), various issues can arise, such as incorrect paths or insufficient permissions. Here's how to handle errors gracefully:
Output:
Error reading directory: ENOENT: no such file or directory, scandir 'C:\invalid\path'If the application doesn't have permission to read a directory, it will throw a permission error::
Output:
Permission error: ENOENT: no such file or directory, scandir 'C:\restricted\path'The fs.readdir() method in Node.js is an efficient, non-blocking way to read the contents of a directory. It provides flexibility with options like withFileTypes to return file objects. Proper error handling is essential to avoid issues with invalid paths or permissions. It’s a straightforward method for managing file system operations in Node.js.