Node.js中从Windows卷GUID名称路径查找文件的问题
问题原因与解决方案
你遇到的问题不是操作失误,glob本身并不支持Windows的卷GUID路径格式(也就是\\?\Volume{...}\这种形式的路径)。
为什么会这样?
glob工具的底层路径解析逻辑主要针对常规的盘符路径(比如C:\、D:\)设计,它无法正确识别Windows的这种扩展长度卷GUID路径作为根目录,所以递归搜索**\*.json时会找不到目标文件。
可行的解决方案
1. 将卷GUID路径映射为驱动器号
这是最简单的办法,用Windows的subst命令把卷GUID路径绑定到一个空闲的驱动器号上:
# 把卷路径映射到Z盘 subst Z: \\?\Volume{56D4B0E2-0000-0000-0000-00A861000000}\
之后把rootDir改成Z:\dir1,再用你的原有glob代码就能正常搜索了。使用完成后可以解除映射:
subst Z: /d
2. 用Node.js原生fs模块实现递归搜索
如果不想映射盘符,可以自己写递归遍历逻辑,Node.js的fs模块是支持扩展长度路径的:
const fs = require('fs').promises; const path = require('path'); async function scanJsonFiles(targetDir) { let jsonFiles = []; const directoryEntries = await fs.readdir(targetDir, { withFileTypes: true }); for (const entry of directoryEntries) { const fullPath = path.join(targetDir, entry.name); if (entry.isDirectory()) { // 递归遍历子目录 jsonFiles = jsonFiles.concat(await scanJsonFiles(fullPath)); } else if (entry.isFile() && path.extname(fullPath) === '.json') { jsonFiles.push(fullPath); } } return jsonFiles; } // 使用示例 const rootDir = '\\\\?\\Volume{56D4B0E2-0000-0000-0000-00A861000000}\\dir1'; scanJsonFiles(rootDir) .then(files => console.log('找到的JSON文件:', files)) .catch(err => console.error('搜索出错:', err));
3. 换用支持扩展路径的第三方glob库
有些第三方glob工具对Windows路径的支持更完善,比如fast-glob,它能够处理卷GUID这类扩展长度路径:
const fg = require('fast-glob'); const rootDir = '\\\\?\\Volume{56D4B0E2-0000-0000-0000-00A861000000}\\dir1'; fg(`${rootDir}\\**\\*.json`) .then(files => console.log('找到的JSON文件:', files)) .catch(err => console.error('搜索出错:', err));
内容的提问来源于stack exchange,提问作者Haapavuo
相关产品推荐
相关产品推荐

