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

如何在JavaScript中访问项目根目录下子文件夹内的JSON文件?

修改路径访问子文件夹中的JSON文件

看起来你已经有了基础的VS Code扩展代码来读取JSON配置,现在只需要调整路径拼接逻辑,把子文件夹名称加入进去就能访问到目标文件了。这里是修改后的完整代码:

function getConfiguredData(keyName) { 
  let data = undefined; 
  let folderPath = vscode.workspace.rootPath; 
  if (folderPath) { 
    console.log(`folderPath: ${folderPath}`); 
    // 把目标子文件夹名称加入路径拼接
    const jsonFilePath = path.join(folderPath, 'someFolder', 'test.json');
    if (fs.existsSync(jsonFilePath)) { 
      data = JSON.parse(fs.readFileSync(jsonFilePath, 'utf8'))[keyName]; 
    }
  }
  return data; // 补充原代码缺失的返回逻辑,确保能拿到数据
}

关键修改点:

  • 新增jsonFilePath变量,通过path.join(folderPath, 'someFolder', 'test.json')拼接完整路径:path.join会自动适配Windows、Linux/macOS等不同系统的路径分隔符,避免手动拼接路径时出现跨平台兼容问题。
  • 将原来判断folderPath是否存在的逻辑,改为判断拼接后的完整JSON文件路径,让文件存在性检查更精准。

针对多JSON文件的扩展性建议:

如果后续有多个子文件夹或JSON文件需要处理,建议把文件夹路径抽成可维护的常量,或者封装成通用工具函数,减少重复代码:

// 把常用的JSON文件存放目录抽成常量,后续修改只需改这里
const JSON_STORAGE_FOLDER = 'someFolder';

function getJsonFileData(fileName, keyName) {
  let data = undefined;
  const workspaceRoot = vscode.workspace.rootPath;
  if (workspaceRoot) {
    const fullFilePath = path.join(workspaceRoot, JSON_STORAGE_FOLDER, fileName);
    if (fs.existsSync(fullFilePath)) {
      data = JSON.parse(fs.readFileSync(fullFilePath, 'utf8'))[keyName];
    }
  }
  return data;
}

// 调用示例:读取不同JSON文件
const testConfig = getJsonFileData('test.json', 'yourTargetKey');
const otherConfig = getJsonFileData('other.json', 'anotherKey');

这样不管后续新增多少JSON文件,只需要调用工具函数并传入文件名即可,不用重复写路径拼接的逻辑。

内容的提问来源于stack exchange,提问作者B-Durmaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:39:57