Blocking Code

Okay. So, Node.js is single thread, and it shouldn't scare you. That's actually a good thing because a lot of complexity is eliminated by using the single threaded environment.

But, it's still possible to write blocking code in Node.js. And when you have single threaded environment, writing blocking code will choke your single process or...and so you need to be very careful to avoid writing blocking code.

Consider this example. And you can open it in "blocking.js", and you can just run that file. Now, I want you to compare your numbers with my numbers. I get anywhere from 100 ms to 1,000 ms. So, that's a lot and what you see, it's obvious that this is a blocking code. I have a for loop where the var of i goes from one to a big number. And then, Iā€™m not doing anything, but still that's a blocking process which blocks my system.

Unfortunately, a lot of blocking code is not as obvious as a for loop with a bazillion of iterations. What is happening in this example, is that we have some blocking code buried inside of the module.

So, fs is a core module, but almost each method in that module has an evil twin. So, readFile would be an asynchronous method, but readFileSync is an evil twin.