Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

361
Views
Why is NodeJs cluster module not working?

So basically I am building an express server and I recently looked into the topic of scaling NodeJS apps. One of the first things I saw was the built in cluster module to take advantage of all the threads of the machine's processor. Here is my code of the implementation I've made:

import cluster from "cluster";
import { cpus } from "os";

import dotenv from "dotenv";
dotenv.config();

import express, { Express } from "express";
import log from "./logger";
import database from "./database";
import router from "./router";

const app: Express = express();

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

const port = <number>(<unknown>process.env.PORT);
const host = <string>process.env.HOST;

const numCPU = cpus().length;
if (cluster.isPrimary) {
   for (let i = 0; i < numCPU; i++) {
      cluster.fork();
   }

   cluster.on("listening", (worker) => {
      // Not printing anything
      console.log(worker.process.pid);
   });

   cluster.on("exit", (worker, code, signal) => {
      log.error(`Worker ${worker.process.pid} died. Starting a new worker...`);
      cluster.fork();
   });
} else {
   app.listen(port, host, () => {
      // Only prints this once.
      log.info(`Server ${process.pid} listening at http://${host}:${port}`);
      database();
      router(app);
   });
}

The problem is that the cluster.isPrimary block never runs meaning of course that no other processes are forked by the cluster. However when I use cluster.isMaster, everything works exactly as intended. But since isMaster is deprecated and is replaced by isPrimary, thats what I'm trying to use but it just doesn't work.

Solutions I've tried that don't work:

  1. Kill all node processes on my machine.
  2. Remove everything from this main file leaving just the barebone app and cluster configuration.

What am I doing wrong?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Its most likely the version of node you are running. isPrimary is only available in versions 16+ and you most likely have the LTS version which is v14

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!