You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

关键说明

  1. 路径拼接:使用path.join替代手动拼接,它会自动处理不同平台的路径分隔符,以及folderPath是否带尾斜杠、filePath是否带头斜杠的情况,生成标准路径。
  2. 相对路径检查:通过path.relative获取文件相对于目标目录的路径,我们只需要验证这个相对路径的结构:
    • 正则/^[^/]+\/[^/]+\.json$/确保相对路径只有一个/,即仅包含一级子目录和JSON文件,没有更深的嵌套层级。
    • [^/]+匹配任意不含斜杠的字符串(目录名或文件名),保证路径中不会出现多余的层级。

内容的提问来源于stack exchange,提问作者Shiv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 22:31:04