Node.js写入JSON文件报错:无法为不存在的对象创建新字段
Hey there, let's break down why you're hitting this error and how to fix it quickly.
Error: Can't make new fields in object if it doesn't exist
The Root Cause
The core issue here is that fs.readFile is asynchronous — it doesn't pause your code while it reads the file from disk. By the time your code reaches these lines:
if (!xp[usr]) xp[usr] = {xpp: 0}; xp[usr].xpp++;
the xp variable is still undefined (since the file read hasn't finished yet). Trying to access properties on an undefined value throws that frustrating error.
Solution 1: Wrap Dependent Code in the Read Callback
The simplest fix is to move all code that uses xp inside the fs.readFile callback. This guarantees xp is only accessed after the file has been successfully read and parsed:
const fs = require('fs'); // Don't forget to require fs if you haven't already fs.readFile('./xp.json', 'utf8', (err, data ) => { if (err) { console.error(err); return; // Exit early if file read fails } let xp = JSON.parse(data); const usr = m['id']; // Clean up the log with template literals console.log(`${m['id']} ${m['channel_id']} ${m['username']}`); if (!xp[usr]) { xp[usr] = {xpp: 0}; } xp[usr].xpp++; fs.writeFile("./xp.json", JSON.stringify(xp), (err) => { if (err) console.error(err); }); });
Solution 2: Use Async/Await for Cleaner Code (Node.js 10+)
If you prefer more linear, readable code over nested callbacks, use Node.js's promise-based file system API with async/await:
const fs = require('fs').promises; // Use promise-powered fs methods async function updateUserXP(m) { try { // Wait for the file to read before proceeding const data = await fs.readFile('./xp.json', 'utf8'); let xp = JSON.parse(data); const usr = m['id']; console.log(`${m['id']} ${m['channel_id']} ${m['username']}`); if (!xp[usr]) { xp[usr] = {xpp: 0}; } xp[usr].xpp++; // Wait for the file to write before finishing await fs.writeFile("./xp.json", JSON.stringify(xp)); } catch (err) { console.error(err); // Catch any errors in one place } } // Call the function with your message object updateUserXP(m);
Quick Extra Tip
Make sure your xp.json file exists and starts with a valid empty object {} if there are no users yet — otherwise the initial JSON.parse will throw an error when the file is empty.
内容的提问来源于stack exchange,提问作者Bjelke

