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

JavaScript类写入config.json内容被覆盖,期望保留多组输入数据

Fixing Your Config Class Output Issue

Hey there, let's walk through why your current code isn't producing the output you want, and how to fix it step by step:

What's Going Wrong?

You've got two key issues causing the unexpected output:

  1. File Overwrites Every Time: Each call to fs.writeFile completely replaces the contents of config.json—so only the last put call's data ends up in the file.
  2. Incorrect Object Structure: Your code creates objects with fixed keys input1 and input2, but you actually want the first argument (like site_name) to be the key, and the second argument to be its corresponding value.

This is the standard approach for config files—we'll read existing config (if it exists), merge new values into it, then write the updated config back. I'll use synchronous methods here for simplicity, but you can switch to async if needed:

const fs = require('fs');
const path = require('path');

// Capitalize class name (follows standard JS conventions)
class Config {
  static put(key, value) {
    const configFilePath = path.resolve('./config.json');
    let currentConfig = {};

    // Read existing config if the file exists
    try {
      const fileContent = fs.readFileSync(configFilePath, 'utf8');
      currentConfig = JSON.parse(fileContent);
    } catch (err) {
      console.log('No existing config found—starting fresh');
    }

    // Add or update the new key-value pair
    currentConfig[key] = value;

    // Write the merged config back, formatted for readability
    fs.writeFileSync(
      configFilePath,
      JSON.stringify(currentConfig, null, 2),
      'utf8'
    );
    console.log('Config updated successfully');
  }
}

// Test the updated class
Config.put('site_name', 'Blog');
Config.put('maintenance', false);
Config.put('age', 30);
Config.put('meta', {"description": "lorem ipsum"});

Resulting config.json

This will give you a clean, valid JSON object that's easy to work with:

{
  "site_name": "Blog",
  "maintenance": false,
  "age": 30,
  "meta": {
    "description": "lorem ipsum"
  }
}

Solution 2: Append Individual Objects (If You Need That Exact Format)

If you specifically want separate objects (one per line, matching your original expected output), we can use appendFileSync instead of overwriting. Note: This isn't valid JSON (it's a stream of JSON objects), so you'll need custom logic to read it later:

const fs = require('fs');
const path = require('path');

class Config {
  static put(key, value) {
    const configFilePath = path.resolve('./config.json');
    // Create the key-value object you intended
    const configEntry = { [key]: value };
    // Append the object to the file, with a newline for readability
    fs.appendFileSync(
      configFilePath,
      JSON.stringify(configEntry, null, 2) + '\n',
      'utf8'
    );
    console.log('Config entry added');
  }
}

// Resulting config.json content:
// { "site_name": "Blog" }
// { "maintenance": false }
// { "age": 30 }
// { "meta": { "description": "lorem ipsum" } }

Quick Notes

  • I used synchronous file methods (readFileSync, writeFileSync) here because they make the logic easier to follow for simple config tasks. For production code with heavy I/O, switch to async methods like fs.promises.readFile paired with async/await.
  • JSON.stringify(..., null, 2) adds indentation to make the config file human-readable—feel free to remove the 2 if you want minified JSON.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:53:27