summaryrefslogtreecommitdiff
path: root/tests/specs/node/worker_threads/auto_exits.mjs
blob: e434f59f794205d6a19f61ed03de038690b85428 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { isMainThread, parentPort, Worker } from "node:worker_threads";

function onMessageOneshot() {
  console.log("Got message from main thread!");
  parentPort.off("message", onMessageOneshot);
}

if (isMainThread) {
  // This re-loads the current file inside a Worker instance.
  const w = new Worker(import.meta.filename);

  setTimeout(() => {
    w.postMessage("Hello! I am from the main thread.");
  }, 500);
} else {
  console.log("Inside Worker!");
  console.log(isMainThread); // Prints 'false'.
  parentPort.on("message", onMessageOneshot);
}