WillEridian
WillEridian

Reputation: 87

Cannot write to JSON in Nodejs

I'm trying to make a live JSON database of IDs and a tag. The Database refreshes by reading from the JSON file and I have traced my problem to Nodejs not writing to disk, and I don't quite know why.

This is my reading operation, and yes there is a file there with proper syntax.

        let dbraw = fs.readFileSync('db.json');
        var db = JSON.parse(dbraw);

This is my writing operation, where I need to save the updates to disk.

                        var authorid = msg.author.id
                        db[authorid] = "M";
                        fs.writeFileSync('db.json', JSON.stringify(db));

Am I doing something wrong? Is it a simple error I am just forgetting? Is there an easier/more efficient way to do this I am forgetting about? I can't seem to figure out what exactly is going wrong, but it has something to do with these two bits. There are no errors in my console, just the blank JSON file it reads every time on the Read Operation.

Upvotes: 1

Views: 984

Answers (2)

suchitra nair
suchitra nair

Reputation: 555

Here's a simple block that does what is desired

const fs = require('fs');
let file_path = __dirname + '/db.json',
dbraw = fs.readFileSync(file_path),
db = JSON.parse(dbraw),
authorid = 'abc';
console.log(db);
db[authorid] = "M";
fs.writeFileSync(file_path, JSON.stringify(db));
dbraw = fs.readFileSync(file_path), db = JSON.parse(dbraw)
console.log(db);

I've added a couple of log statements for debugging. This works and so there may be something else that's missing or incorrect in your flow. The most probable issue would be that of different path references as pointed out by jfriend00 in the comment to your question.

As for better solutions, following are a few suggestions

  1. use require for the json directly instead of file read if the file is small which will do the parsing for you
  2. Use async fs functions
  3. Stream the file if it's big in size
  4. See if you can use a cache like redis or database as a storage means to reduce your app's serialization and deserialization overhead

Upvotes: 0

amir
amir

Reputation: 218

There is a problem with your JSON file's path.

Try using __dirname.

__dirname tells you the absolute path of the directory containing the currently executing file.
source (DigitalOcean)

Example:

If the JSON file is in the root directory:

let dbraw = fs.readFileSync(__dirname + '/db.json');
var db = JSON.parse(dbraw);

If the JSON file is in a subdirectory:

let dbraw = fs.readFileSync(__dirname + '/myJsonFolder/' + 'db.json');
var db = JSON.parse(dbraw);

Side note: I suggest you read about Google Firestore, as it will be a faster way to work with real time updates.

Upvotes: 1

Related Questions