Supercharge Node.js with Worker Threads
We all know that Node.js is fantastic for I/O-bound tasks ie. reading and writing data. But what about CPU intensive tasks where complex calculations are required. For sure that’s gonna be slow. That’s where Worker Threads come into the picture.
Worker Threads let you take full advantage of multi-core CPUs and run tasks in parallel without blocking your main thread. In this blog, I will try to help you understand and get started with Worker Threads.
In a Node.js application, Worker Threads run on a separate thread performing any task that you assign it side by side your main thread which is spinning the node server. Think of it giving your app multiple hands to handle work simultaneously.
By using them, you will gain better performance, enable concurrency and achieve better scaling of your application.
How to use Worker Threads?
- Set Up Your Project
Ensure you have node installed on your system. Any version higher that 10.5.0 will do. Check the node version using below command.
node -v
If not installed, get the latest version of node from https://nodejs.org. Then create a new directory and open it in you favorite text editor.
2. Create a Basic Worker Thread
Create a file index.js and write this simple code to launch a worker.
const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.on('message', (msg) => console.log(`Main thread got message: ${msg}`));
worker.postMessage('Hello Worker!');
} else {
parentPort.on('message', (msg) => {
console.log(`Worker received message: ${msg}`);
parentPort.postMessage('Hello from the Worker!');
});
}
3. Run the Application
Execute the index.js file
node index.js
You will see -
Worker received message: Hello Worker!
Main thread got message: Hello from the Worker!
So when your main thread starts, it creates a new worker and sends the message Hello Worker! to the worker thread. It also registers a listener on the line before logging the message worker receives.
The worker once started will run the else part of the code. Here, it registers a listener on the main thread to listen to the messages sent by the worker. at the same time it sends a message Hello from the Worker! to the main thread.
Worker Threads let you unlock the full potential of multi-core CPUs in your Node.js app. They’re perfect for offloading CPU-heavy tasks, improving performance, and ensuring your main thread remains responsive.
With just a few lines of code, you can get started with Worker Threads today and boost your app’s performance instantly. Happy coding!