全局字符串比较

Glob string comparison

我有一个 glob 字符串和一个文件路径,是否可以测试文件路径以查看字符串是否与 glob 匹配?

let path = ['/home/location/file.scss','/home/location/file.cat'];
let pattern = '**/*.{sass,scss}';

path.forEach(file => {
    if(/* Test success */) {
        // read file and process it's content
    }
});

你会使用正则表达式吗?因为您可以将模式转换为正则表达式 /\.s[ac]ss$/i,然后执行

path.forEach(file => {
  if (file.match(pattern)) {
  }
});

还有glob-to-regexp,以防你必须在 glob 中编写模式。

安装minimatchnpm install minimatch

然后你可以用

匹配你的测试数组
var minimatch = require("minimatch");

let path = ['/home/location/file.scss','/home/location/file.cat'];
let pattern = '**/*.{sass,scss}';

path.forEach(file => {
    if(minimatch(file, pattern) {
        // read file and process it's content
    }
});

虽然如果你只是想对文件做些什么,我会以不同的方式使用它,或者使用 http://github.com/isaacs/node-glob