JavaScript类写入config.json内容被覆盖,期望保留多组输入数据
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:
- File Overwrites Every Time: Each call to
fs.writeFilecompletely replaces the contents ofconfig.json—so only the lastputcall's data ends up in the file. - Incorrect Object Structure: Your code creates objects with fixed keys
input1andinput2, but you actually want the first argument (likesite_name) to be the key, and the second argument to be its corresponding value.
Solution 1: Merge Configs into a Single Valid JSON Object (Recommended)
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 likefs.promises.readFilepaired withasync/await. JSON.stringify(..., null, 2)adds indentation to make the config file human-readable—feel free to remove the2if you want minified JSON.
内容的提问来源于stack exchange,提问作者okky

