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.

1 Answer 1

3

Synchronously, you can append to files using fs.appendFileSync

const fs = require('fs');
fs.appendFileSync(filename, json);
Sign up to request clarification or add additional context in comments.

1 Comment

The asynchronous answer is here as well : stackoverflow.com/questions/10685998/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.