Node js clusters can't be imported in typescript

Viewed 1959

I'm imported clusters as import * as cluster from "cluster"; and when I'm trying to check cluster.isMaster in if(cluster.isMaster){} I'm getting this error

TS2339: Property 'isMaster' does not exist on type 'typeof import("cluster")'.

and import cluster from "cluster"; I'm getting that cluster is undefined. How can I solve the problem in ts, how can I import clusters in ts and use them?

4 Answers

I have got the same issue today, and this workaround worked for me:

import * as _cluster from 'cluster';
const cluster = _cluster as unknown as _cluster.Cluster; // typings fix

Install @types/node as dev dependency

npm install @types/node --save-dev

Sample Code:

import cluster from 'cluster'
import { cpus } from 'os'

import App from "./App"
import config from "./config/config"


const app = new App().express
const port = config.port

if (cluster.isPrimary === true) { 
    // .isPrimary with node v16.0.0 or above
    // .isMaster (depreciated) with older version
    const CPUS: any = cpus()
    CPUS.forEach(() => cluster.fork())
} else {
    app.listen(port, () => {
        console.log(`API is listening on http://localhost:${port} on ${process.pid}`);
    });
}

You need to import the cluster constant that is exported by default in the file

/node_modules/@types/node/cluster.d.ts

isMaster is not a named import of the the cluster module. It's a property of the default export of the module.

This means that you want to import the default export, and not as import * as.

import cluster from "cluster"
if (cluster.isMaster) { console.log('master') }

Playground

I faced the same issue today and solved it by setting "esModuleInterop": true in tsconfig.json.

Related