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

问题描述 投票:0回答:1

我有这样的文件结构:

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

我想得到style.css文件

javascript node.js
1个回答
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']

这种方法是同步的。

© www.soinside.com 2019 - 2024. All rights reserved.