Get the Number of System CPU Cores Using NodeJS

Are you using Node.js and need to get the number of CPU cores the operating system has?
Luckily, Node.js has a built-in way for you to do this with their os module, which provides a lot of cool operating-system related utility methods.
Those methods include a way to analyze the CPU cores on the machine your code is running on.
The module can be used in your Node.js by requiring it like this:
const os = require("os")
Since this is an internal Node.js module, you don't need to install any npm dependencies.
To get information about a system's CPU's, we will use the os.cpu() method that will return an array of objects with information about each CPU in it.
Here's what the code looks like:
const cpuData = os.cpus()
If you log that cpuData variable with console.log(cpuData), this will be logged:
    model: 'Intel(R) Core(TM) i5-4690K CPU @ 3.50GHz',
    speed: 4268,
    times: {
      user: 150659900,
      nice: 277600,
      sys: 65754400,
      idle: 487990800,
      irq: 0
    model: 'Intel(R) Core(TM) i5-4690K CPU @ 3.50GHz',
    speed: 4281,
    times: {
      user: 149682200,
      nice: 208500,
      sys: 64688700,
      idle: 27844500,
      irq: 0
Each CPU object in the array has these values:
  • model: string of the CPU model
  • speed: number of the CPU speed in MHz
  • user: number of milliseconds the CPU has spent in user mode
  • nice: number of milliseconds the CPU has spent in nice mode
  • sys: number of milliseconds the CPU has spent in sys mode
  • idle: number of milliseconds the CPU has spent in idle mode
  • irq: number of milliseconds the CPU has spent in irq mode
Given this array of objects, we can get the number of CPU's by getting the length of the array.
Here's what the code would look like:
const numOfCpus = os.cpus().length
When you log the numOfCpus, it will print a number for the amount of CPUs the system your Node.js code is running in has.
Hopefully, this was helpful in your coding endeavors.
Thanks for reading and happy coding!