Node.js - How to Backup Variables to a file and reobtain it on server relaunch?

I think the title says it all. But I want to explain further.

Let's say, I have a running nodejs server which contains a variable that will contain (almost) all data that the server will store. If I want to do a server restart (due to some reasons), how do I backup the variables so that it's safe to close the nodejs server, and to relaunch it with the variables that contains the data when I closed it?

Regards, JoshuaLangit123

Here's some pseudo code to achieve what you want to do:

  1. At startup, read data.json and assign the value of it to your single data variable:

    var data = JSON.parse(fs.readFileSync('data.json'));
    
  2. When the app is closed using Ctrl-C you can use this handler to write the single data variable back to data.json.

    process.on( 'SIGINT', function() {
      fs.writeFileSync('data.json', JSON.stringify(data));
      process.exit();
    })
    

This depends on so many things. Usually what you do is use a database (mongodb, mysql, whatever) to store application state.. Users, session, etc

If you really do want to dump all the variables to a file that can be read/written to (which I think sounds like a really, really, really bad idea, but hard to know for sure unless I knew what you were doing) you could make a single object that you put all the variables into, which you can json-ify and write to disk.

and then you read that file again (or require it even) when the node instance is started again.