Introduction

This tutorial introduce the synchronous recursive directory search using Node.js fs.readdirSync.

Solution

Parallel loop to sync directory search

The following example shows a synchronous way to search file with js extension.

Filesystem = require('fs');
 
var findFile, jsFiles, rootDir;
jsFiles = [];
 
findFile = function(dir)
{
    Filesystem.readdirSync(dir).forEach(function(file) {
    var stat;
    stat = Filesystem.statSync("" + dir + "/" + file);
    if (stat.isDirectory())
    {
      return findFile("" + dir + "/" + file);
    }
    else if (file.split('.').pop() === 'js')
    {
      return jsFiles.push("" + dir + "/" + file);
    }
  });
};
 
// test it out on home directory 
findFile(process.env.HOME);
console.log(jsFiles);

Above example written in CoffeeScript

jsFiles = []
 
 
# Method to find js file recursively
findFile = (dir) ->
    Filesystem.readdirSync(dir).forEach (file) ->
        stat = Filesystem.statSync "/"
        if stat.isDirectory() then findFile("/")
        else if file.split('.').pop() is 'js'
            jsFiles.push "/"
 
# test it out on home directory
findFile process.env.HOME

References & Resources

  • N/A