Nodejs - concurrently read json files

I’ve been playing around with the integrated fs module. As far as I know, it can read and write to json files upon starting the node server. Anyway to do this concurrently? I want to console.log to see if the new changes I make to the file but because the server is already running, it will load the original json file without the new changes. Here is my code so far

const fs = require('fs');

var posts;
fs.readFile('./posts.json', 'utf8', function (err, data) {
  posts = JSON.parse(data).posts;
});

console.log(posts);

Any suggestions? Thanks!

Hi @Liamgrossman, you can also read the file while handling a request so that you’ll always get its most recent contents… there is no server in your code snippet though, this is just a script that runs once and then exits. Actually, you won’t even get the file contents logged as the call to console.log() will be executed before the readFile() callback that is assigning the data to the posts variable.

What exactly do you mean with concurrently here? Do you want to read several files at the same time?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.