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

TypeScript修改JSON文件时整文件被覆盖而非单条数据的问题

JSON文件被整个覆盖而非修改指定条目的问题解决

问题根源

核心问题出在异步函数的错误实现上:

  • jsonReader标记为async但未正确返回Promise,还错误混合了fs.promises.readFile(Promise风格)与回调函数,导致它实际返回undefined。
  • updateReferenceNumber中没有await jsonReader的结果,直接对undefined执行赋值操作,最终生成仅含目标产品的新对象,写入后自然覆盖了整个原文件。
  • 由于jsonReader的逻辑未按预期执行,所以内部的console.log不会输出。

修正后的代码

第一步:修复jsonReader函数

async jsonReader(filepath: string) {
  try {
    const fileData = await fs.promises.readFile(filepath);
    const data = JSON.parse(fileData.toString());
    console.log("Got to the jsonReader and I'm returning:", data);
    return data;
  } catch (err) {
    console.log("Error reading/parsing JSON:", err);
    throw err;
  }
}

第二步:修复updateReferenceNumber函数

async updateReferenceNumber(productName: string, newReference: string){
  try {
    const data = await this.jsonReader('./filepath.json');
    data[productName] = newReference;
    await fs.promises.writeFile('./filepath.json', JSON.stringify(data, null, 2));
    console.log("I got here and the reference number is currently:", data[productName]);
    console.log("-------------------------------------------");
  } catch (err) {
    console.log("Error updating JSON:", err);
  }
}

关键修正点说明

  1. jsonReader的正确实现:

    • 移除回调函数,用await处理fs.promises.readFile的Promise结果
    • 读取到的fileData是Buffer,需转成字符串再做JSON解析
    • 统一用try/catch处理错误,并抛出错误让上层函数捕获
  2. updateReferenceNumber的异步等待:

    • 必须用await调用jsonReader,确保拿到真实的JSON数据后再修改
    • 改用fs.promises.writeFile配合await,避免回调嵌套,同时保证写入完成后再执行后续逻辑

验证结果

修正后调用await jsonHelper.updateReferenceNumber("ECMadrid", "NewRef");,原JSON文件会变成:

{
  "ECMadrid": "NewRef",
  "ECParis": "tbd2"
}

同时jsonReader中的console.log会正常输出读取到的原始数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 07:12:37