How do you get a list of the names of all files present in a directory in Node.js?
Quickly fetch all file names from a directory in Node.js using either fs.readdirSync
for a synchronous approach or fs.readdir
for handling operations asynchronously. Both methods are integral parts of the built-in fs
module.
Synchronous example:
Asynchronous example:
Take note that these methods simply return the file names, not their full paths or any specific details. Moreover, correct handling of the err
parameter is pivotal to manage potential errors in the asynchronous version.
Deep Dive and Edge Cases
Let's venture on to discover more advanced usage scenarios and address potential edge cases.
File Details Included (Node.js v10.10.0+)
With Node.js version 10.10.0 and onwards, you can use { withFileTypes: true }
option with the fs.readdir
and fs.readdirSync
methods to also get the file details. This is a handy trick to distinguish between files and directories.
Recursive wonders: Directory Traversal
For recursive traversal of subdirectories and listing all files therein, you can roll your own recursive function. Or, you know, use a pre-made package like walk
.
Example using recursion with fs
:
The Special Agent: Pattern Matching with glob
The glob
package is like your pattern-matching secret agent. It helps listing files in a directory that match a specified pattern, say, all JavaScript files.
Promise-land: Promise-based Alternatives
The util.promisify
method or the latest fs.promises
API give you access to the Promise-land. Enjoy the Promises when listing files.
Or using fs.promises
directly:
Was this article helpful?