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.
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.
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?