Middle+
Have you ever worked with Worker Threads in Node.js?
sobes.tech AI
Answer from AI
Worker Threads in Node.js are used to perform CPU-intensive tasks in separate threads to avoid blocking the main event loop. This is especially useful when you need to process heavy computations or operations concurrently that are not related to asynchronous input/output.
Example of creating and using a Worker Thread:
const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.on('message', (msg) => console.log(`Result from worker: ${msg}`));
worker.postMessage('Start work');
} else {
parentPort.on('message', (msg) => {
// Perform heavy task
let result = 0;
for (let i = 0; i < 1e9; i++) {
result += i;
}
parentPort.postMessage(result);
});
}
Thus, Worker Threads allow efficient parallelization of tasks, improving the performance of Node.js applications.