使用Node.js与正则表达式查找二级目录下.json文件的问题排查
问题修复:仅匹配指定目录下一级子目录中的JSON文件
你的代码存在两个核心问题:
- 路径拼接逻辑错误:手动拼接
folderPath和filePath时未处理斜杠,导致路径格式混乱,比如folderPath不带尾斜杠时,会和filePath开头部分连在一起,让正则误判。 - 正则逻辑错误:原正则匹配的是整个路径的前两个目录段+JSON文件,而非
folderPath之后的一级子目录下的JSON文件,完全不符合需求。
修正后的代码
const path = require('path'); function checkIfLastTwoLevelsAreJson(folderPath, filePath) { // 用path模块正确拼接路径,自动处理斜杠问题 const fullPath = path.join(folderPath, filePath); // 获取相对于目标目录的路径 const relativePath = path.relative(folderPath, fullPath); // 正则匹配:仅允许一层子目录 + JSON文件,无更深嵌套 const regex = /^[^/]+\/[^/]+\.json$/; return regex.test(relativePath); } const folderPath = "/user/admin"; const filePath1 = "en-us/dummy.json"; const filePath2 = "en-us/hello/dummy.json"; const filePath3 = "en-us/test/hello/dummy.json"; console.log(checkIfLastTwoLevelsAreJson(folderPath, filePath1)); // true console.log(checkIfLastTwoLevelsAreJson(folderPath, filePath2)); // false console.log(checkIfLastTwoLevelsAreJson(folderPath, filePath3)); // false
关键说明
- 路径拼接:使用
path.join替代手动拼接,它会自动处理不同平台的路径分隔符,以及folderPath是否带尾斜杠、filePath是否带头斜杠的情况,生成标准路径。 - 相对路径检查:通过
path.relative获取文件相对于目标目录的路径,我们只需要验证这个相对路径的结构:- 正则
/^[^/]+\/[^/]+\.json$/确保相对路径只有一个/,即仅包含一级子目录和JSON文件,没有更深的嵌套层级。 [^/]+匹配任意不含斜杠的字符串(目录名或文件名),保证路径中不会出现多余的层级。
- 正则
内容的提问来源于stack exchange,提问作者Shiv
相关产品推荐
相关产品推荐

