![]() |
VOOZH | about |
The fs.readdirSync() method is used to synchronously read the contents of a given directory. The method returns an array with all the file names or objects in the directory. The options argument can be used to change the format in which the files are returned from the method.
fs.readdirSync( path, options )Parameters: This method accept two parameters as mentioned above and described below:
Returns: It returns an array of String.
Below examples illustrate the fs.readdirSync() method in Node.js:
Example 1: This example uses fs.readdirSync() method to return the file names or file objects in the directory.
Output:
Current directory filenames:
CONTRUBUTIONS.txt
index.html
index.js
package.json
README.md
Current directory files:
Dirent { name: 'CONTRUBUTIONS.txt', [Symbol(type)]: 1 }
Dirent { name: 'index.html', [Symbol(type)]: 1 }
Dirent { name: 'index.js', [Symbol(type)]: 1 }
Dirent { name: 'package.json', [Symbol(type)]: 1 }
Dirent { name: 'README.md', [Symbol(type)]: 1 }
Example 2: This example uses fs.readdirSync() method to return only the filenames with the ".md" extension.
Output:
Filenames with the .md extension:
README.md
Issues such as incorrect directory paths, insufficient permissions, or inaccessible files can cause errors when using the fs.readdirSync() method. Below are examples of how to handle such errors.
Example:
Output:
Error reading directory: ENOENT: no such file or directory, scandir 'C:\invalid\path'If the application does not have permission to read a directory, it will throw a permission error. Here’s how you can handle it:
Output:
Permission error: ENOENT: no such file or directory, scandir 'C:\restricted\path'The fs.readdirSync() method is a powerful tool for synchronously reading the contents of a directory in Node.js. It's particularly useful when you need to ensure that directory reading is completed before proceeding with the next steps in your code. While it should be used with caution in scenarios where blocking operations might affect performance, it's an excellent choice for simple tasks and scripts that require immediate and reliable access to directory contents.