Course contentsShow
← JavaScript
Lesson 2159 of 2,72345. Workers and ConcurrencyFree lesson

Creating a Worker with worker_threads

Use the Worker constructor from the worker_threads module to spawn a new thread with a script file.

Creating a Worker with worker_threads

You'll learn how to spawn a new thread in Node.js by constructing a Worker with a script file.

Now that you understand what worker threads are in Node.js, it's time to actually create one. The worker_threads module provides a Worker constructor that spawns a new thread running a separate JavaScript file. Think of it like launching a mini Node.js process dedicated to running one specific script—except it's a thread within your main process, sharing memory more efficiently.

The Worker Constructor

To create a worker thread, you import the Worker class from the built-in worker_threads module and instantiate it with the path to your worker script:

const { Worker } = require('worker_threads');

const worker = new Worker('./my-worker.js');

This immediately spawns a new thread that begins executing my-worker.js. The path can be relative to the current file or absolute. The worker runs independently, and your main thread continues executing without waiting.

A Complete Example

main.js:

const { Worker } = require('worker_threads');

const worker = new Worker('./worker.js');
console.log('Main thread: Worker spawned');

worker.js:

console.log('Worker thread: Hello from the worker!');

When you run node main.js, both messages appear—one from the main thread, one from the worker thread running in parallel.

What Happens Under the Hood

The Worker constructor creates a new JavaScript execution context with its own event loop and memory space (though some memory can be shared). The worker script runs from top to bottom, just like any Node.js script, but in its own thread.

Key Takeaway: Use new Worker('./script.js') from the worker_threads module to spawn a new thread that executes a separate JavaScript file independently of your main thread.