Skip to content
← Back to Community
Read/WriteFile keeps rolling back in node
Profile icon
glugau

Hi everyone,

I'm building a discord bot, and I save data to a JSON file.
The problem is that it appears that the data sometimes rolls back to an older value, and I think it is because of repl.it.

I read files with fs.ReadFileSync(), then I edit the data and I write with fs.WriteFile().

I want to point out that it works most of the time, but then it suddenly rolls back to an old version, which defeats the purpose of the bot which is to store the amount of messages a user sent (it is for a small server so I don't feel like I need a database)

Thank you for any help!

Voters
Profile icon
glugau
Comments
hotnewtop
Profile icon
19wintersp

File edits will only be saved if the owner is on the Repl. You may need to use a database such as ReplDB. ReplDB is built into your Repl, so it should be relatively easy to setup.

Profile icon
glugau

@19wintersp I saw this, but I'm annoyed to rebuild all of my code. I'll give it a try :/

Profile icon
19wintersp

@glugau Surely you should just be able to replace fs.readFileSync with await db.get and put them inside an async function?

Profile icon
glugau

@19wintersp I'm looking into it but I don't understand how to get a value as db.get doesn't return the value. Can you help?

Profile icon
19wintersp

@glugau db.get returns a Promise, which resolves to the data. You should convert the function to an async function and do await db.get instead.

Profile icon
ErrorNoInternet

@19wintersp Is there a way to setup multiple databases for 1 REPL?

Profile icon
19wintersp

@ErrorNoInternet Each repl will have one ReplDB instance connected to it; one approach to treating it as multiple could be to namespace keys, like this:

KeyValue
foo:key1value1
foo:key2value2
bar:key1value1
bar:key2value2

So the first two are in the foo database, and the second two in the bar database. You will probably have to do this manually, unless you want to update the source code of the library.