I am learning Node.js and I have read that Node.js is single threaded and non-blocking.
I have a good background in JavaScript and I do understand the callbacks, but what I don't really understand is how Node.js can be single threaded and run code in the background. Isn't that contradictory?
Because if Node.js is single threaded it can still only perform one task at the time. So if it runs something in the background it has to stop the current task to process something in the background, right?
How does that work practically?
Working of single-threaded non-blocking IO:This thread reads the client request, processes the request, performs any blocking IO operations if needed, and prepares the final response to be sent back to the server. The event loop sends this response back to the respective client.
No. NodeJs is not single threaded. The NodeJs event loop operates on a single thread yes, but the async blocking operations are delegated to separate worker threads. These threads notify the main thread when they are done processing.
Our Node. js applications are only sort of single-threaded, in reality. We can run things in parallel, but we don't create threads or sync them.
Node.js is a single-threaded, non-blocking asynchronous concurrent runtime environment.
What "in the background" really means in terms of NodeJS is that things get put on a todo list for later. Whenever Node is done with what it's doing it picks from the top of the todo list. This is why doing anything that actually IS blocking can wreck your day. Everything that's happening "in the background" (actually just waiting on the todo list) gets stopped until the blocking task is complete.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With