在Windows环境下使用NodeJS的fast-glob不正确执行的问题
fast-glob是NodeJS中的一个非常高效的文件遍历工具,通过它在文件系统中方便的指定和筛选文件,它采用 Unix Bash shell 使用的规则返回与一组定义的指定模式匹配的路径名,并进行了一些简化,同时以任意顺序返回结果。它支持同步、Promise 和 Stream API。在Windows环境下使用NodeJS中的模块fast-glob时却发生了异常的情况,即筛选遍历的文件总是空的情况。示例代码如下:
const glob = require("fast-glob");
let { include_patterns, ignore_patterns } = files.length
? get_files_to_build(files)
: get_all_files_to_build(apps);
glob(include_patterns, { ignore: ignore_patterns }).then((files) => {
let output_path = assets_path;
if (files.length === 0) {
console.log('没有文件匹配模式:' , include_patterns);
} else {
console.log('匹配到的文件:', files);
}
let file_map = {};
let style_file_map = {};
let rtl_style_file_map = {};
for (let file of files) {
console.log(file);
let relative_app_path = path.relative(apps_path, file);
let app = relative_app_path.split(path.sep)[0];
let extension = path.extname(file);
let output_name = path.basename(file, extension);
if ([".css", ".scss", ".less", ".sass", ".styl"].includes(extension)) {
output_name = path.join("css", output_name);
} else if ([".js", ".ts"].includes(extension)) {
output_name = path.join("js", output_name);
}
output_name = path.join(app, "dist", output_name);
if (
Object.keys(file_map).includes(output_name) ||
Object.keys(style_file_map).includes(output_name)
) {
log_warn(`Duplicate output file ${output_name} generated from ${file}`);
}
if ([".css", ".scss", ".less", ".sass", ".styl"].includes(extension)) {
style_file_map[output_name] = file;
rtl_style_file_map[output_name.replace("/css/", "/css-rtl/")] = file;
} else {
file_map[output_name] = file;
}
}
let build = build_files({
files: file_map,
outdir: output_path,
});
let style_build = build_style_files({
files: style_file_map,
outdir: output_path,
});
let rtl_style_build = build_style_files({
files: rtl_style_file_map,
outdir: output_path,
rtl_style: true,
});
return Promise.all([build, style_build, rtl_style_build]);
});
在Windows环境下执行上面的代码时,筛选的文件总是空的集合。但是在Linux环境下却能正常执行。经过分析发现fast-glob不支持Windows中路径使用反斜杠分隔路径,因此需要将路径的反斜杠全部替换为正常的斜杠。以下说明来自如下链接:https://github.com/mrmlnc/fast-glob/issues/237
The fast-glob package since 3.0.0 does not support backslashes as path separator.
const filepath = path.join('directory', 'file-name.txt');
// directory\\file-name.txt
Release notes:
Only forward-slashes in glob expression. Previously, we convert all slashes to the forward-slashes, which did not allow the use of escaping. See pattern syntax section in the README.md file.
Documentation:
- https://github.com/mrmlnc/fast-glob#pattern-syntax
- https://github.com/mrmlnc/fast-glob#how-to-write-patterns-on-windows
js 将反斜杠(\)替换为正斜杠(/)可以使用下面的方法:
只替换一次 var str = uploads\fce43fewr32d3e3d; var str = str.replace(\\, ‘/’) 全部替换 var str = \uploads\fce43fewr32d3e3d; var str = str.replace(/\\/g, '/');

浙公网安备 33010602011771号