Simplest way to store a small amount of persistent state

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.

3 Likes

Oh, wow, that’s slick and smart and simple! Is that a pretty standard thing to do or is that your own invention (or could be both)?

Either way, thanks so much for the tip!

1 Like

@dreev, take a look at this thread: https://stackoverflow.com/questions/14939289/easy-way-to-store-json-under-node-js

1 Like

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)
2 Likes