Node.js - Get number of processors available

Linuxnode.js

Linux Problem Overview


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?

Linux Solutions


Solution 1 - Linux

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.

See the code below:

const os = require('os')
const cpuCount = os.cpus().length

Solution 2 - Linux

var os = require('os'),
cpuCount = os.cpus().length;

Solution 3 - Linux

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLouisKView Question on Stackoverflow
Solution 1 - LinuxYoguView Answer on Stackoverflow
Solution 2 - LinuxrainabbaView Answer on Stackoverflow
Solution 3 - LinuxchadhamreView Answer on Stackoverflow