0

i am working on a function createOrLoadJSON() which should check the application for a existing json file. IF the file not exists, he shall create the file "userData.json" and add data into it. This whole process should be dynamical, means if i add more objData the following data should append to the json obj instead of recreating the "userData.json" again and overriding the first item after a reload.

the code looks like this:

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() {},
  },
};

How can i do this? I have absolutely no idea.

Deniz
  • 1,435
  • 14
  • 29

1 Answers1

3

Synchronously, you can append to files using fs.appendFileSync

const fs = require('fs');
fs.appendFileSync(filename, json);
EDToaster
  • 3,160
  • 3
  • 16
  • 25
  • 1
    The asynchronous answer is here as well : https://stackoverflow.com/questions/10685998/how-to-update-a-value-in-a-json-file-and-save-it-through-node-js – JohnSnow Jul 10 '19 at 21:19