gpt4 book ai didi

javascript - 如果存在则加载 json 并附加数据,而不是重新创建和覆盖 json 文件

转载 作者:行者123 更新时间:2023-11-28 17:02:22 24 4
gpt4 key购买 nike

我正在开发一个函数createOrLoadJSON(),它应该检查应用程序是否存在现有的 json 文件。如果该文件不存在,他应创建文件“userData.json”并向其中添加数据。整个过程应该是动态的,意味着如果我添加更多 objData,以下数据应该附加到 json obj,而不是再次重新创建“userData.json”并在重新加载后覆盖第一个项目。

代码如下所示:

import userDataJson from './../data/userData.json';
export const userDataControllerMixin = {
data() {
return {
users: [],
userDataAbsPath: 'src/data/userData.json',
};
},
mounted() {
this.getUsers();
},
methods: {
getUsers() {
return userDataJson;
},
User(user, salary) {
this[user] = {
salary: [Number(salary)],
};
// TODO: ADD THESE INTO A PROTOTYPE IN A OTHER MIXIN
// income: [income],
// expenses: [expenses],
},
// GET INPUT FROM USERS DIALOGBOX
getInput(inputName, inputSalary) {
const userName = this.inputName;
const userSalary = this.inputSalary;
const user = new this.User(userName, userSalary);
this.users.push(user);
this.createOrLoadJSON(this.users);
},
// CREATES A JSON WITH DATA FROM THE USERS
createOrLoadJSON(data) {
const fs = require('fs');
const json = JSON.stringify(data, null, '\t');

// TODO: if JSON exists skip creating part and load the existing json file here
if (fs.existsSync(this.userDataAbsPath)) {
console.log('file exists, dont create file, use the existing one and append data');
// LOGIC FOR NOT CREATE THE JSON AGAIN, INSTEAD USE THE EXISTING FILE AS INITIAL AND ALLOW TO APPEND DATA


// read file and add next entry
// ADD new entry instead of override the first one
} else {
console.log('file not exists, so create file');
fs.writeFile(this.userDataAbsPath, json, (error) => {
if (error !== null) {
console.log(error);
}
});
}
this.postUsers();
},
// OUTPRINTS DATA FROM userObj.json
postUsers() {},
},
};

我该怎么做?我完全不知道。

最佳答案

您可以使用 fs.appendFileSync 同步附加到文件

const fs = require('fs');
fs.appendFileSync(filename, json);

关于javascript - 如果存在则加载 json 并附加数据,而不是重新创建和覆盖 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56978727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com