Skip to content
Advertisement

Why use readFileAsync to read file with json inside in Node.js?

I was learning Node.js and was watching Node.js course where an author used the below code:

const tours = JSON.parse(fs.readFileSync('data.json'));

app.get('/api/v1/tours', (req, res)=>{
res.status(200).json({tours.tours})
}))

As you can see the code above, we first try to parse the json by reading the file synchronously. The author said that if we use const tours = JSON.parse(fs.readFileSync('data.json')); inside callback of get() then event loop would be blocked since callbacks are executed by event loop. But since the author put

const tours = `JSON.parse(fs.readFileSync('data.json'));` 

outside of callback, that code will be considered as top-level code which is not executed by event loop. And what is a bit confusing is that since const tours = JSON.parse(fs.readFileSync('data.json')); is top-level code, the author said that it is ok to use synchronous version of readFile. I thought synchronous readFile is best to avoid being used since it is blocking. Is it true that synchronous top-level code is not blocking even if use readFileSync or is the author wrong by using readFileSync even as top-level code?

Advertisement

Answer

Every code in Node.js runs in the event loop. Top level code as well, and so the event loop is going to be blocked. Nothing changes. The reason it is somewhat OK to do it at the top level is because the code is being blocked only once, during the initial code run. Inside .get() you would block your entire application during every request. That would be a disaster.

That being said the code gives false impression that you should not worry about blocking at the top level. This is wrong. It increases your application startup time. And if you stack many such calls you can see noticeable lag during the startup. The rule of thumb is: always avoid synchronous I/O in Node.js, no matter what.

IMO the course is seriously flawed.

Advertisement