Ah, Node.
Let me give you a little bit information about how Node works. So, Node operates on a single thread. You can imagine as a rail line, but in the case of Node.js, only one train can run on it at a time. Therefore, single-threaded.
Now, to offer some great features, NodeJS needed a workaround for this; they came up with the idea of observers, and an event loop. In the observer design pattern, a father process, keeps on observing (looking for changes) an object; this goes on infinitely.
So, whenever an event is complete, a registered callback is fired. Let's take an example:
const obj = {
doStuff() {
...
emitEvent( 'complete' );
...
};
obj.on( 'complete', () => {
console.log( 'Done!' );
} );
As you can see, using this method, we can very easily achieve pseudo-multithreading; in the sense that you can execute multiple blocking (anything which doesn't allow the function stack to progress further; say XMLHttpRequest) functions.
This entire thing: Attach callback, on event complete, fire callback, repeat is called the event-driven nature of Node.js.
Again, if you have any other doubts, ask me! I hope this helps! :)
I think this article might be able to break it down easily for you: medium.com/@BenDiuguid/asynchronous-adventures-in…
Hello. May I suggest this answer on StackOverflow? Even if outdated it should shed some light about NodeJS' nature.
Shreyansh Pandey
node, coffee and everything in between
Sandeep Panda
co-founder, Hashnode
Event Driven means changes in state or events determine application control flow. Unlike languages like Java, Node.js is single threaded. It has an Event Loop that listens to various events and executes registered callbacks. Imagine how you attach callbacks in JavaScript :
Once window loads, your callback is invoked by JavaScript. Same principles apply to Node.js. For example, imagine you are doing some file I/O. Node can't just keep waiting until some data is read from the file. This will block the thread as Node.js is single threaded. So, the solution is doing things asynchronously. The
fsmodule lets you register a callback that will be called once data is read from the file.This way your callback gets executed (asynchronously) once the operation is done (an event signals this) and it doesn't have to block the thread. You will frequently find these kinds of APIs in modules like socket, http etc.
TIP
Read this.