You can use node fs.*Sync()
methods which will block until the operation is done.
The readdirSync
function will give you a list of files (and subdirectories, which are also files) in a directory and statSync
will tell you, if it's a directory or a file.
You should be aware that your script can do nothing else while doing the blocking operations though. So do not export and use that code as a function in a bigger application.
If you want to reuse it, you should write your code in an asynchronous fashion (i.e. use callbacks and handle your state / values accordingly). Or use one of the npm modules that implement the necessary functionality ("walk" seems to be a good search keyword for your use-case).