Suppose I want to store a single integer and have it persist across app restarts. I could write it to a file but that seems susceptible to race conditions and is maybe a little ugly, I don’t know. Maybe my app will need an actual database soon enough and I should just use one now even though that’s overkill for the immediate use case?
What do you all recommend?
PS: I see lots of options at https://glitch.com/@storage but it’s kind of overwhelming and I can’t tell if it’s up to date.
I usually start with a simple database that is a JSON object that gets written to the filesystem so that when the app shuts down the data is persisted.
Here’s an example:
const db = require("./db.json") // create a `db.json` file that contains {}
if(!db.users) db.users = [] // initialize an array, if you want db.users to be an array
const fs = require("fs")
const save = () => fs.writeFile("./db.json", JSON.stringify(db), () => {})
// remember to also run save() every time you make a change to the db object
I believe you won’t run into any race conditions, since it’s literally just an object in memory that you’re modifying. Then, run save() every time you make a change so that the data gets persisted in the filesystem. When the app restarts, db will reinitialize from the ./db.json file.
Ah nice! I think I first picked it up from this gist.
I usually keep the top-level db variable as an object, and then I have db.users, db.projects, etc. as arrays of objects. Then I can use array methods to find things easily, like:
const user = db.users.find(u => u.email === EMAIL)