简体   繁体   English

node.js目录搜索名称为的文件

[英]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. 我需要编写一个node.js应用程序的帮助,该应用程序搜索其名称包含指定字符串的当前目录下的所有子目录。

for example the user want to search all directories that have the string 'test' in it. 例如,用户想要搜索其中包含字符串“ test”的所有目录。

what is the js code i need to use? 我需要使用什么js代码?

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 看看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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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