使用通配符匹配查找文件

时间:2014-01-23 21:22:58

标签: node.js

在node.js中,我可以列出具有匹配的通配符的文件,如

fs.readdirSync('C:/tmp/*.csv')?

我没有从fs documention找到有关外卡匹配的信息。

5 个答案:

答案 0 :(得分:55)

Node核心未涵盖此问题。您可以查看this module了解您的目标。 npmjs.org也是查找各种模块的绝佳资源。

用法

var glob = require("glob")

// options is optional
glob("**/*.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.
})

答案 1 :(得分:28)

如果您不想向项目添加新的依赖项(例如$ awk '{lc=tolower($0)} (lc ~ /^de/) && (lc ~ /de$/)' file dende DEnaDE de.de de ),则可以使用普通的js / node函数,例如:

glob

var files = fs.readdirSync('C:/tmp').filter(fn => fn.endsWith('.csv')); 可能有助于进行更复杂的比较

答案 2 :(得分:8)

如果glob不是你想要的,或者有点令人困惑,那么还有glob-fs。该文档涵盖了许多使用场景和示例。

// sync 
var files = glob.readdirSync('*.js', {});

// async 
glob.readdir('*.js', function(err, files) {
  console.log(files);
});

// stream 
glob.readdirStream('*.js', {})
  .on('data', function(file) {
    console.log(file);
  });

// promise 
glob.readdirPromise('*.js')
  .then(function(files) {
    console.log(file);
  });

答案 3 :(得分:0)

仅当您要通过正则表达式搜索文件(用于复杂匹配)时,然后考虑使用file-regex,它支持递归搜索和并发控制(以实现更快的结果)。

样品用量

import FindFiles from 'file-regex'

// This will find all the files with extension .js
// in the given directory
const result = await FindFiles(__dirname, /\.js$/);
console.log(result)

答案 4 :(得分:-5)

不要重新发明轮子,如果你在{nix上ls工具可以轻松地执行此操作(node api docs

var options = {
  cwd: process.cwd(),
}
require('child_process')
.exec('ls -1 *.csv', options, function(err, stdout, stderr){
  if(err){ console.log(stderr); throw err };
  // remove any trailing newline, otherwise last element will be "":
  stdout = stdout.replace(/\n$/, '');
  var files = stdout.split('\n');
});
相关问题