Я работаю над функцией 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() {},
},
};
Как я могу это сделать?Понятия не имею.