Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - single thread, non-blocking?

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?

like image 837
Mathieu David Avatar asked Apr 28 '15 06:04

Mathieu David


People also ask

How node js single threaded non-blocking IO works?

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.

Is node JS really single threaded?

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.

Is node js single threaded or multithreaded Why?

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.

Is node JS asynchronous single threaded?

Node.js is a single-threaded, non-blocking asynchronous concurrent runtime environment.


1 Answers

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.

like image 89
Lucas Avatar answered Oct 11 '22 01:10

Lucas