WeCodeAcademy

Node.js Child Processes and Workers

ExampleNode.js
const { execSync, spawnSync } = require("child_process");
const { Worker, isMainThread, parentPort, workerData } = require("worker_threads");

if (isMainThread) {
  console.log(execSync("echo hello from a shell").toString().trim());
  const r = spawnSync("node", ["-e", "console.log(6 * 7)"]);
  console.log(r.stdout.toString().trim(), r.status);

  const worker = new Worker(__filename, { workerData: 10 });
  worker.on("message", (m) => console.log("worker says", m));
  worker.on("exit", () => console.log("worker finished"));
} else {
  let total = 0;
  for (let i = 1; i <= workerData; i++) total += i;
  parentPort.postMessage(total);
}
Output
hello from a shell
42 0
worker says 55
worker finished

A child process runs another program. A worker thread runs JavaScript on another thread so heavy computing does not block the server.

Quick check

Why use a worker thread?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.