简体   繁体   中英

node.js directory search for file with name

i need help writing a node.js application that searches for all sub directories under the current directory which their names contain the specified string.

for example the user want to search all directories that have the string 'test' in it.

what is the js code i need to use?

i try using this:

var walk = function(dir) {
var results = []
var list = fs.readdirSync(dir)
list.forEach(function(file) {
    file = dir + '/' + file
    var stat = fs.statSync(file)
    if (stat && stat.isDirectory()) results = results.concat(walk(file))
    else results.push(file)
})
return results
}

Take a look at node-glob

In your case you could use it like this. This pattern will give you all files in the folder that contain at least once test in the name.

var glob = require("glob")

glob("+(test).js", options, function (er, files) {
  // files is an array of filenames.
  // If the `nonull` option is set, and nothing
  // was found, then files is ["**/*.js"]
  // er is an error object or null.
  if (er) {
      // omg something went wrong
      throw new Exception(er);
  }
  var requiredFiles = files.map(function(filename) {
      return require(filename);
  });
  // do something with the required files
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM