fs.readdirSync() is a Node.js function that synchronously reads the contents of a directory. This means it pauses the execution of your code until it has finished reading the directory’s files and subdirectories.
How to read directory contents in Node.js
Key takeaways:
fs.readdirSync()reads directory contents synchronously. This means it blocks other code until the operation is complete.The function takes a path and optional options as arguments. The path specifies the directory to read, and the options can include encoding for file names.
fs.readdirSync()returns an array of file and subdirectory names. This array can then be used to perform further operations on the directory contents.
Node.js fs module provides many functions to deal with directories and their content. For this Answer, we’ll cover the fs.readdirSync() method, whose primary function is to read the contents of a folder, whether they be files or subfolders. As the name suggests, this is done synchronously, but in the coming sections, we’ll see learn how to do this asynchronously as well.
Syntax
The following is the general syntax of fs.readdirSync(). To access the contents of any folder, we’ll pass the path to that directory as an argument to the fs.readdirSync() function. We also pass any additional object, labeled as options in the code below. The optional object contains optional parameters like a string which specifies the encoding for the file.
fs.readdirSync(my_folder_path, options)
This method works synchronously and returns an object containing all the folder contents. This means it won’t function parallel with other code parts. This method will prevent all other code sections from executing while reading the folder contents. Hence, it’s blocking. We can loop through the obtained files and manipulate them as we like.
Lines 1–2: We import the
fsandpathmodules.Lines 4–5: Next, we save the folder’s path in
my_directory_pathvariable.Lines 6–8: Lastly, we call
readdirSyncfunction, passing itmy_directory_pathas an argument, and then store the object returned indisplay_directory; we’ll use this variable to append all file names with the folder’s path and log them to the screen.
However, this isn’t the only way to expose file system data; we can achieve the same with callbacks or promises, as shown below. However, we’ll use the asynchronous counterpart of readdirSync() called readdir(). Note that asynchronous execution is how parallelism is achieved.
Asynchronous with fs.readdir() using callbacks
The following shows the general syntax for implementing fs.readdir(). We’ll use a callback function that will take the error object and files_in_directory—the object containing all the folder content—as arguments.
Lines 1–3: We import the
fsmodule first. Then, we store the folder path in the variableeducative_folder.Lines 5–16: With
fs.existsSync, we verify whether the folder exists; if true, we’ll move into theifblock, wherefs.readdir()function is called. We pass the folder path and the callback function as arguments. If the folder has been read correctly inside the callback, all the file names within that directory will be logged to the screen. Otherwise, an error will be shown.Lines 18–31: If the folder does not exist at the specified path,
fs.mkdir(educative_folder)creates the directory at that path and then calls thefs.readdir()function in the same way.
Asynchronous with fs.readdir() using Promises
Another way of doing all the above would have been to use promises.
Lines 1–5: Firstly, we acquire the
pathandnode:fs/promisesmodules.Lines 6–9: Secondly, we save the folder path as
my_directory_path, passing it as an argument to the promised version ofreaddir(). If the promise resolves successfully, we can access the object containing all the files in the.thenblock and log the file names to the console.Lines 11–13: If the promise is rejected, we can perform error handling in the
.catchblock; in our case, we simply log the error to the screen.
Conclusion
In conclusion, we saw how to read folder content using the fs.readdirSync() which operates synchronously. However, if we want to adapt the same method asynchronously, we’d use its counterpart fs.readdir().
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What does fs readdirSync do?
What does fs.readFileSync return?
How to check if dir exists in Node.js
Free Resources