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

如何用TypeScript向JSON文件数组追加元素?解决重复数组问题

解决JSON文件追加元素生成多个独立数组的问题

问题描述

需要实现函数向JSON文件添加元素,需处理两种场景:

  • JSON文件为空(无任何字符,或文件不存在)
  • JSON文件已包含合法数组

当前实现逻辑为:判断文件为空时创建新数组写入;若文件有内容则解析后追加元素再写入。但多次调用后,文件中生成了多个独立数组,而非在同一数组中追加元素。

问题根源

核心问题出在WriteToFile方法中使用了fs.appendFile:

  • 第一次调用时,写入第一个数组的JSON字符串
  • 第二次调用时,直接将新的数组JSON字符串追加到文件末尾,而非覆盖原有内容
  • 最终文件内容是多个独立的JSON数组拼接,而非单个包含所有元素的数组

修复方案

1. 修改文件写入方式:用writeFile替代appendFile

每次处理完成后,我们需要将完整的合并后数组覆盖写入文件,而非追加内容。fs.writeFile会替换文件原有内容,正好符合需求。

2. 完善异常处理与边界情况

  • 处理文件不存在的场景(ReadFile可能返回空或抛出异常)
  • 处理文件内容不是合法JSON的情况(比如之前错误写入的无效内容)

修改后的代码示例

优化后的WriteToFile方法

/**
 * @param filePath  { enum } this is preset in the File system class
 * @param payload   { any } this will be stringfied in the method
 */
async WriteToFile(filePath: PathFile, payload: any) {
    try {
        this.CheckArgumentPathIsCorrect(filePath);

        const fileBuildJoin = path.join(__dirname, '..', 'database', filePath);
        // 替换appendFile为writeFile,实现覆盖写入
        const writeToFile = promisify(fs.writeFile);

        let stringfiedPayload: string;
        if (typeof payload === 'object') {
            stringfiedPayload = JSON.stringify(payload, null, 2); // 格式化输出,可选
        } else if (typeof payload === 'string') {
            stringfiedPayload = payload;
        } else {
            throw new Error('Invalid payload type');
        }

        await writeToFile(fileBuildJoin, stringfiedPayload);
        return 'Success';
        
    } catch (error) {
        this.ErrorHandlingAsync(error as Error, 'Error caught in writing file');
    }
}

优化后的createCategory方法

public async createCategory() {
    try {
        const fileOperations = new FileSystem();
        let tempArray: Category[] = [];

        try {
            const stateOfFile = await fileOperations.ReadFile(PathFile.Categories);
            // 仅当文件内容非空时尝试解析
            if (stateOfFile.trim().length > 0) {
                tempArray = JSON.parse(stateOfFile);
                // 确保解析结果是数组
                if (!Array.isArray(tempArray)) {
                    throw new Error('File content is not a valid array');
                }
            }
        } catch (readError) {
            // 处理文件不存在或内容不是合法JSON的情况,重置为空数组
            tempArray = [];
        }

        // 追加当前元素
        tempArray.push(this);
        await fileOperations.WriteToFile(PathFile.Categories, tempArray);
        
    } catch (error) {
        throw error;
    }
}

说明

  • 替换appendFile为writeFile后,每次写入都会覆盖文件,确保文件中始终只有一个完整的数组
  • 新增的异常处理逻辑可以兼容文件不存在、内容为空或内容无效的场景,避免解析失败导致程序崩溃
  • 可选添加JSON.stringify的格式化参数(null, 2),让文件内容更易读

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 07:25:36