在Windows環境下使用NodeJS的fast-glob不正確執行的問題

培轩發表於2024-04-09
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:
  • https://github.com/mrmlnc/fast-glob/releases/tag/3.0.0

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,  '/');

相關文章