Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท child_process, worker_threads and cluster

Node.js isMainThread and parentPort

Reference for isMainThread, parentPort, threadId and the single-file worker pattern in Node.js worker_threads: how code finds out which thread it runs in.

The node:worker_threads module exports a few values that tell a piece of code where it is running. isMainThread is true in the main thread and false inside a Worker. parentPort is the end of the message channel that connects a worker to the thread that created it; in the main thread it is null. threadId is a number that identifies the thread: 0 for the main thread, then 1, 2, ... for workers in creation order.

Together they allow a single-file worker: one file that starts a copy of itself as a worker and branches on isMainThread. This keeps small examples and tools in one place, and the pattern scales to larger programs where the worker code lives in its own module.

NODE
import { Worker, isMainThread, parentPort } from 'node:worker_threads';

if (isMainThread) {
  new Worker(import.meta.filename);   // run this same file as a worker
} else {
  parentPort.postMessage('hello from the worker');
}

Try it

Node.js One file, two roles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js parentPort in practice: a small task protocol

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

What each value means

Export In the main thread In a worker
isMainThread true false
parentPort null A MessagePort connected to the parent. postMessage() sends to the parent's worker.on('message'); the worker's parentPort.on('message') receives what the parent sent with worker.postMessage().
threadId 0 A positive integer unique among live workers of the process.
workerData null The cloned value passed in options.workerData (see workerData).
resourceLimits {} The limits that apply to this worker.

parentPort is an ordinary MessagePort: it is an event emitter with postMessage(), on('message'), once(), close(), ref() and unref(). It also supports the web-style onmessage property and addEventListener.

Usage notes

  • Listening keeps the worker alive. Adding parentPort.on('message', ...) keeps the worker's event loop busy, so it never exits on its own. Stop it by calling parentPort.close(), calling process.exit() in the worker, or calling worker.terminate() in the parent.
  • once versus on. A worker that handles exactly one request can use parentPort.once('message', ...); after it fires and no other work remains, the worker exits naturally.
  • Order of messages is preserved in each direction. If the parent posts a message before the worker has registered its listener, the message is queued until the first listener is attached.
  • Do not use parentPort in the main thread. It is null, so parentPort.postMessage() throws a TypeError. Branch on isMainThread first (or on parentPort === null).
  • threadId is not a pid. It only identifies the thread inside one process. Worker 1 is the first worker created; ids of finished workers are not reused while the process lives.
  • Nested workers. A worker may start workers of its own. isMainThread is still false for each of them, and their parentPort talks to the worker that created them.
  • ES modules versus CommonJS. In CommonJS the self-reference is __filename; in ES modules use import.meta.filename (or fileURLToPath(import.meta.url)).