Nikhil
Nikhil

Reputation: 1325

Get a specific file from the sub directory in Node js recursively

I have a file structure like this:

  lib
   |->Code
       |-> Style
            |-> style.css

I want to get style.css file

Upvotes: 0

Views: 3319

Answers (1)

erikvimz
erikvimz

Reputation: 5476

The following code does a recursive search inside ./ (change it appropriately) and returns an array of absolute file names ending with style.css.

var fs = require('fs');
var path = require('path');

var searchRecursive = function(dir, pattern) {
  // This is where we store pattern matches of all files inside the directory
  var results = [];

  // Read contents of directory
  fs.readdirSync(dir).forEach(function (dirInner) {
    // Obtain absolute path
    dirInner = path.resolve(dir, dirInner);

    // Get stats to determine if path is a directory or a file
    var stat = fs.statSync(dirInner);

    // If path is a directory, scan it and combine results
    if (stat.isDirectory()) {
      results = results.concat(searchRecursive(dirInner, pattern));
    }

    // If path is a file and ends with pattern then push it onto results
    if (stat.isFile() && dirInner.endsWith(pattern)) {
      results.push(dirInner);
    }
  });

  return results;
};

var files = searchRecursive('./', 'style.css'); // replace dir and pattern
                                                // as you seem fit

console.log(files); // e.g.: ['C:\\You\\Dir\\subdir1\\subdir2\\style.css']

This approach is synchronous.

Upvotes: 3

Related Questions