以递归方式从Node js中的子目录中获取特定文件

时间:2017-12-19 11:40:34

标签: javascript node.js

我有这样的文件结构:

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

我想获得style.css文件

1 个答案:

答案 0 :(得分:1)

以下代码在./ 中进行递归搜索(适当更改)并返回以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']

这种方法是同步的。