Avoid code duplication and reusing code is always an admirable goal. However, in some occasions, it's not a bad idea to duplicate a little bit of code in order to make your software better.
When writing a Node app, accessing a directory listing is fairly simple: the fs.readdir
command provides a list of objects in a directory, and a call to fs.stat
will tell you whether each object is a directory or a file.
That's fairly straightforward, but recursing (especially when using callbacks) can require some mental yoga. Each directory needs to keep track of how many subdirectories it expects to receive callbacks for and results need to be aggregated in pieces rather than sequentially.
When I needed a recursive directory listing this past week, I was tempted to use a library: why solve a solved problem? The glob
library provides this functionality with very little effort: