How threads in Node.js work?

How threads in Node.js work?
Average rating: 0
(0 votes)

Thanks! You’ve rated this material!

How can a single-threaded Node.js be compared to the multithreaded backends? Backend languages that support multithreading have all kinds of mechanisms for syncing values between threads and other thread-oriented features. Nowadays many big companies choose Node as their backend, with its single-threaded nature. To know why we have to understand how threads in Node.js work?

Node.js has two kinds of threads: the main thread handled by the event loop and several auxiliary threads in the worker pool.

Event loop is the mechanism that takes functions and registers to be executed at some point in the future. It operates in the same thread as the JavaScript code. When a JavaScript operation blocks the thread, the event loop is blocked too.

Worker pool is a model that handles separate threads, which then simultaneously perform the task and return the result to the event loop. The event loop then executes the provided callback with said result.

To send the data to the other thread, we use the port.postMessage() method. Communication between threads is made through ports, which are instances of the MessagePort class and enable event-based communication.

The worker_threads module is a package that creates fully functional multithreaded Node.js applications. To start using thread workers, we have to import the worker_threads module. To know how to do that, check the original article by Maciej Cieślar.

By the way, did you know that most of the significant Node.js features were first experimental?

Rate this article, if you like it

Thanks! You’ve rated this material!

Got a project? Let's discuss it!

    Kyiv Sofiivska 1/2a, 01001, Kyiv, Ukraine
    Dnipro Hlinky 2, of. 1003, 49000, Dnipro, Ukraine
    Kharkiv Otakara Yarosha 22, 61000, Kharkiv, Ukraine