Home » Javascript » How can I save or update to a file after adding a new object to it?

How can I save or update to a file after adding a new object to it?

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’m trying to update/save a js file after a forum submission.

My application is an electron / react desktop app. I have a bunch of objects saved in a .js file each object represents a help file.

HelpData.js looks similar to this.

const HelpData = [
  {
    name: '',
    menu: '',
    content: ''
  },
  {
    name: '',
    menu: '',
    content: ''
  },
]

export default HelpData;

My component loads in the data found in this file and pushes a new object into the array of objects. Everything works fine when the application is running, but when you exit the application the new file that was added is lost.

I need to figure out a way to save the file added to HelpData.js

Here is the function that adds the file to array of object:

  handleSubmit(e) {
        e.preventDefault();

        let newFile = { name: '', menu: '', title: '', path: '', content: '', section: 'Section IV', video: 'n' }
        newFile.name = this.state.name;
        newFile.menu = this.state.menu;
        newFile.title = this.state.title;
        newFile.path = this.state.path;
        newFile.content = this.state.content;

        HelpData.(newFile);
        // now that the new file has been pushed onto HelpData array, I need to save the file HelpData.js.  This is what I'm not sure how to do in javascript.

   } 

After I push the new file into the HelpData array, how can I either rewrite HelpData.js and save the file, or write directly into the file and save?

Answers: