Node.js Internal Mechanism

Node.js is a JavaScript runtime environment.The Node run-time environment includes everything you need to execute a program written in JavaScript.Its  built on Chrome’s V8 JavaScript engine.

Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.I/O refers to input/output. It can be anything ranging from reading/writing local files to making an HTTP request to an API.I/O takes time and hence blocks other functions.

All Node JS applications uses “Single Threaded Event Loop Model” architecture to handle multiple concurrent clients. So Yes NodeJS is single threaded, but this is a half truth, actually it is event-driven and single-threaded with background workers. The main event loop is single-threaded but most of the I/O works run on separate threads, because the I/O APIs in Node.js are asynchronous/non-blocking by design, in order to accommodate the event loop.

NodeJs operate asynchronously and uses the Event-loop mechanism

Event Loop is a constantly running process that checks if the call stack is empty. Imagine it like a clock and every time it ticks it looks at the Call Stack and if it is empty it looks into the Event Queue. If there is something in the event queue that is waiting it is moved to the call stack. If not, then nothing happens.

Please consider below post. In what order do you think the following code will run?

 

setTimeout(() => console.log(‘first’), 0)

console.log(‘second’)

Some people think that because set timeout is called with 0 (zero) it should run immediately. In fact in this specific example you will see “second” printed out before “first”. JavaScript sees the setTimeout and says “Well, I should add this to my Event Table and continue executing”. It will then go through the Event Table, Event Queue and wait for the Event Loop to tick in order to run.Node.js uses the same approach internally and operate asynchronously.