84

This is really just to satisfy curiosity, and see if there's a better way to do this.

On my Windows 8 box, Node's process.env object has a NUMBER_OF_PROCESSORS property, on my Linux box it doesn't.

Obviously different platforms have different environment variables, that much is a given, but it seems like NUMBER_OF_PROCESSORS would be a useful thing to have regardless.

My quick fix for Linux was spawning a child process to run the nproc command, but I'd like to avoid using a callback for simply getting the number of processors. Seems like there must be a simpler way.

What have other people done to solve this?

0

6 Answers 6

150

It's built into node and called os.cpus()

Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of milliseconds the CPU/core spent in: user, nice, sys, idle, and irq).

The length of this array is the number of "processors" in the system. Most systems only have one CPU, so that's the number of cores of that CPU.

2
  • 13
    This list also includes virtual cores. An Intel i7 will show 8 cores logical out of 4 physical cores due to Hyper-Threading Technology.
    – Mário
    May 23, 2017 at 5:20
  • 5
    This is number of cpus in the system; not number available as returned by nproc May 28, 2018 at 6:40
94
const os = require('os'),
const cpuCount = os.cpus().length;
0
13

In your CLI you can run the following log the # of cores on the machine.

node -e 'console.log(require("os").cpus().length)'
1

If you are using ES6 module:

import os from 'os';
const cpuCount = os.cpus().length;

If you're using CommonJs:

const cpuCount = require("os").cpus().length;
0

in Node.js you can get the number of system logical processors by doing any of the following;

const os = require("node:os");
  1. available parallelism

    const availableProcessors = os.availableParallelism();
    console.log(availableProcessors);
    
  2. logical cpu core array of object

    const cpuCount = os.cpus().length;
    console.log(cpuCount);
    
-1

I'd say: running under Linux, you should use nproc. The user, if he so chooses, can then limit your app to a number of processors just by setting the environment variable OMP_THREAD_LIMIT. If you use os.cpus().length, this is not possible.

I am - right now - running an npm build for the first time. I could get around that until now... And it almost locked up my machin, b/c of too many threads and too high memory consumption. And I would've more liked to limit the processes/threads than to limit the memory. But I couldn't. Think about the user!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.