加载json(如果存在)并追加数据,而不是重新创建和覆盖json文件

时间:2019-07-10 21:14:13

标签: javascript json vue.js filesystems

我正在使用函数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() {},
  },
};

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

1 个答案:

答案 0 :(得分:3)

您可以使用fs.appendFileSync

同步添加到文件
const fs = require('fs');
fs.appendFileSync(filename, json);