【发布时间】:2019-07-11 05:18:37
【问题描述】:
我正在开发一个函数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() {},
},
};
我该怎么做?我完全不知道。
【问题讨论】:
标签: javascript json vue.js filesystems