JavaScript Snippet – Recurse A Directory Synchronously

Recently I took a look at making HTML5 programs that will work on Mac, Linux and Windows via Electron and needed a way to recurse a directory synchronously in Node.js. I ended up with the following code:

The above function allows us to recursively get the contents of a directory. It also provides the ability to filter out files and sub-directories. The following is an example of using it to simply get all files and directories within a specified directory:

var dir = recurseDirSync('/Users/jsmith/Movies');

/*****
// Example directory structure:
{
  isFile: false,
  path: '/Users/jsmith/Movies/',
  stat: ,
  files: [
    {
      isFile: true,
      path: '/Users/jsmith/Movies/Scrooge McDuck.mp4',
      stat: ,
    },
    {
      isFile: false,
      path: '/Users/jsmith/Movies/The Other Movies/',
      stat: ,
      files: [...]
    },
    ...
  ]
}
*****/

As you can see, get the files and sub-directories of a directory is very easy. You can also easily filter with this function. Let’s say we want to only include directories and MP4s:

recurseDirSync('/Users/jsmith/Movies', function(path, isFile, stat) {
  return !isFile || /\.mp4$/i.test(path);
});

Once again, using this helper function makes something that could’ve been complex a lot easier. Feel free to use and even modify this function. :cool:

Leave a Reply

Your email address will not be published. Required fields are marked *


three × 9 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">