我正在使用函数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() {},
},
};
我该怎么做?我完全不知道。
答案 0 :(得分:3)
您可以使用fs.appendFileSync
const fs = require('fs');
fs.appendFileSync(filename, json);