Use localStorage in Node scripts
Persist a small key-value counter across Node processes with localStorage and an explicit backing file, and know when to use another store.
You run a local command twice and want the second process to remember the first run. For a few string values, Node's localStorage gives you key-value operations and handles the backing file.
Give both invocations the same file
Node 25 made Web Storage available without the experimental flag. Pass --localstorage-file with a path to enable persistence. On Node 22, add --experimental-webstorage before the script name.
Save this as visits.mjs.
const key = 'runs'
const previous = Number(localStorage.getItem(key) ?? '0')
const runs = previous + 1
localStorage.setItem(key, String(runs))
console.log(runs)On the first run, the absent key starts the count at zero, and the script prints the incremented value.
node --localstorage-file="$PWD/visits.db" visits.mjs
node --localstorage-file="$PWD/visits.db" visits.mjsIn a fresh directory you see 1 followed by 2, even though each invocation starts a new process.
The storage API takes strings. getItem returns null for an absent key, so the example supplies '0' before calling Number. If you change the stored format later, use a new key or validate the string before you convert it. State from older versions of the script can outlive the code that wrote it.
Pick the file by who owns the state
The example uses the current directory because both commands run from the same place. For a CLI you invoke from several directories, choose an absolute path in the user's state directory. If a counter starts again at 1, check which file each invocation opened before changing the code.
The Node API history records an empty object without a path in Node 25.0.0. Node 26.0.0 made reading the global without a path throw a DOMException. Supply the path before calling any storage methods.
Node writes the backing file unencrypted and caps it at 10 MB. Use it for a last-run timestamp or a display preference. Use a credential store for tokens.
A server process shares this storage across requests. The counter assumes serial runs because the read and write are separate operations. Use a transactional store if multiple processes update the same counter.