Worker Threads
Offload CPU-intensive tasks to worker threads in Node.js to keep your Express server responsive. Includes a reusable worker service and a Fibonacci demo route.
Overview
A production-grade demonstration of Node.js Worker Threads for executing CPU-heavy computations without blocking the main event loop. Ideal for handling complex calculations, image processing, or encryption in scalable Express applications.
Installation
What This Does
Installs a worker-thread utility with Express integration to run CPU-bound tasks (like Fibonacci calculations) off the main thread.
Files & Folders Created
| File / Path | Description |
|---|---|
| /src/worker.js | Defines the CPU-heavy task (Fibonacci example). |
| /src/services/workerService.js | Manages worker thread creation and lifecycle. |
| /src/routes/heavyTask.js | Express route to trigger worker computation. |
| /server.js.example | Example Express server with worker endpoint. |
Files to be modified
| File / Path | Description |
|---|---|
| server.js | Adds a new route /api/calculate-fibonacci using worker threads. |
Configuration
# Environment Variables PORT=3001 NODE_ENV=development
Frontend Integration
You can trigger heavy computations like Fibonacci calculations directly from your frontend (Next.js or React). The computation runs on a worker thread, ensuring the main API remains responsive.
Executes a CPU-intensive Fibonacci calculation in a worker thread and returns the result asynchronously.
Example
1// app/workers/FibonacciClient.jsx (Next.js example)
2'use client';
3import { useState } from 'react';
4
5export default function FibonacciClient() {
6 const [number, setNumber] = useState(40);
7 const [result, setResult] = useState(null);
8 const [loading, setLoading] = useState(false);
9
10 async function calculateFibonacci() {
11 setLoading(true);
12 setResult(null);
13 try {
14 const res = await fetch(`/api/calculate-fibonacci?number=${number}`);
15 const data = await res.json();
16 setResult(data.result);
17 } catch {
18 setResult({ error: 'Failed to fetch result' });
19 } finally {
20 setLoading(false);
21 }
22 }
23
24 return (
25 <div className="p-4 border border-white/10 rounded-lg bg-black/30">
26 <label className="block mb-2 text-sm font-medium">Enter Fibonacci Number:</label>
27 <input
28 type="number"
29 value={number}
30 onChange={(e) => setNumber(e.target.value)}
31 className="px-3 py-2 rounded bg-zinc-900 border border-zinc-700 text-white w-full mb-3"
32 />
33
34 <button
35 onClick={calculateFibonacci}
36 disabled={loading}
37 className="bg-emerald-600 hover:bg-emerald-700 disabled:bg-gray-700 text-white px-4 py-2 rounded font-medium"
38 >
39 {loading ? 'Calculating...' : 'Run Worker'}
40 </button>
41
42 {result && (
43 <div className="mt-4 text-sm text-gray-300">
44 <p>๐งฎ Result: <b>{result.result}</b></p>
45 <p>๐ง Thread ID: {result.threadId}</p>
46 </div>
47 )}
48 </div>
49 );
50}Usage
1// Reuse worker threads for any CPU-heavy task
2const { runWorker } = require('./src/services/workerService');
3const path = require('path');
4
5(async () => {
6 const result = await runWorker({
7 workerPath: path.resolve(__dirname, './src/worker.js'),
8 workerData: 35
9 });
10 console.log('Worker Result:', result);
11})();