1. Spawn a worker
new Worker(path) loads the file and runs its JS on a separate OS thread, in parallel with the main thread.
const worker = new Worker("./worker.js", { workerData: { rows: 1000 } });Typorithm · hard
Step 1 of 8 · intro card
Concurrency
Worker Threads run JavaScript on a separate thread for CPU-bound work. new Worker(path) spawns it, postMessage / parentPort exchange data, workerData seeds the worker at startup, and SharedArrayBuffer lets threads share memory. They are not for I/O — the event loop already handles that.
new Worker("./worker.js") loads a file and runs its JavaScript on a separate OS thread, giving you real parallelism for CPU-bound work like parsing, hashing, or image processing without freezing the main thread.
The two threads talk by message passing: the parent calls worker.postMessage and listens with worker.on("message"), while the worker uses parentPort to receive and reply. workerData carries an initial value provided at spawn time, and a SharedArrayBuffer can share raw memory directly when copying is too slow.
Worker Threads are not for I/O. Reading files or making network calls is already non-blocking via the event loop, so wrapping I/O in a worker adds overhead for no gain — reserve workers for genuinely CPU-bound computation.
new Worker(path) runs JS on a separate thread for CPU work.
postMessage / parentPort exchange data; workerData seeds init.
Not for I/O — the event loop already handles that.
import { Worker } from "node:worker_threads";
const worker = new Worker("./worker.js", { workerData: { rows: 1000 } });
worker.on("message", (result) => console.log("done", result));
worker.postMessage({ start: true });
// worker.js
import { parentPort, workerData } from "node:worker_threads";
parentPort.on("message", () => {
const sum = heavyCompute(workerData.rows);
parentPort.postMessage(sum);
});Connect each part of the code to the concept before you type.
new Worker(path) loads the file and runs its JS on a separate OS thread, in parallel with the main thread.
const worker = new Worker("./worker.js", { workerData: { rows: 1000 } });The main thread listens for messages the worker sends back, picking up the computed result asynchronously.
worker.on("message", (result) => console.log("done", result));postMessage sends data to the worker; values are structured-cloned, so the two threads do not share the object.
worker.postMessage({ start: true });Inside the worker, parentPort is the channel back to the parent and workerData holds the init value passed at spawn time.
import { parentPort, workerData } from "node:worker_threads";Heavy synchronous computation runs here without blocking the main thread's event loop.
const sum = heavyCompute(workerData.rows);Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.