I'm running a server with NodeJS and keeping an account. Since the accounts are kept in the map, the map disappears when the server restarts. I prefer to use 'fs' to solve this. When the server starts, take it from a saved folder and set it to map and save the map to a folder every 30 seconds. How can I do this or do you have any other ideas?
If you use JS objects instead of map you can use JSON.stringify method to convert the object to a string and then store it to file system. Imagine something like this:
const database = {"user1": {"some": "data"}, "user2": {"some": "data"}};
const serializedDatabase = JSON.stringify(database);
fs.writeFileSync("./data/database.json", serializedDatabase);
You can run this code inside setInterval loop to make it run every 30 seconds:
setInterval(() => {
const serializedDatabase = JSON.stringify(database);
fs.writeFileSync("./data/database.json", serializedDatabase);
}, 30 * 1000);
Then, if you want to read the data once you start you application, just require the file:
const database = require("./data/database.json");
You will get your data in memory. Some points:
writeFile should be probably used instead of writeFileSync to make it non-blocking.