On this page

    P

    worker_threads.isMainThread

    History
    Type:boolean

    Is true if this code is not running inside of a Worker thread.

    import { Worker, isMainThread } from 'node:worker_threads';
    
    if (isMainThread) {
      // This re-loads the current file inside a Worker instance.
      new Worker(new URL(import.meta.url));
    } else {
      console.log('Inside Worker!');
      console.log(isMainThread);  // Prints 'false'.
    }
    const { Worker, isMainThread } = require('node:worker_threads');
    
    if (isMainThread) {
      // This re-loads the current file inside a Worker instance.
      new Worker(__filename);
    } else {
      console.log('Inside Worker!');
      console.log(isMainThread);  // Prints 'false'.
    }