0
0
NodejsHow-ToBeginner · 3 min read

How to Get CPU Info in Node.js: Simple Guide

In Node.js, you can get CPU information using the os module's cpus() method, which returns an array of objects describing each CPU core. Each object includes details like model, speed, and times spent in different modes.
📐

Syntax

The os.cpus() method returns an array where each element represents a CPU core. Each element is an object with properties:

  • model: CPU model name
  • speed: CPU speed in MHz
  • times: Object with time spent in user, nice, sys, idle, and irq modes (in milliseconds)
javascript
const os = require('os');
const cpus = os.cpus();
console.log(cpus);
💻

Example

This example shows how to get CPU info and print the model and speed of each core.

javascript
const os = require('os');

const cpus = os.cpus();
cpus.forEach((cpu, index) => {
  console.log(`CPU Core ${index + 1}: ${cpu.model} - ${cpu.speed} MHz`);
});
Output
CPU Core 1: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz - 1992 MHz CPU Core 2: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz - 1992 MHz CPU Core 3: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz - 1992 MHz CPU Core 4: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz - 1992 MHz CPU Core 5: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz - 1992 MHz CPU Core 6: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz - 1992 MHz CPU Core 7: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz - 1992 MHz CPU Core 8: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz - 1992 MHz
⚠️

Common Pitfalls

Common mistakes when getting CPU info in Node.js:

  • Not importing the os module correctly (use import os from 'os' or const os = require('os') depending on your setup).
  • Expecting os.cpus() to return a single object instead of an array of cores.
  • Trying to modify the returned CPU info objects (they are snapshots and should be treated as read-only).
javascript
/* Wrong: expecting a single CPU object */
const os = require('os');
const cpu = os.cpus();
console.log(cpu.model); // undefined because cpu is an array

/* Right: iterate over the array */
const cpus = os.cpus();
cpus.forEach(cpu => console.log(cpu.model));
Output
undefined Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz ... (for each core)
📊

Quick Reference

Summary tips for getting CPU info in Node.js:

  • Use os.cpus() to get an array of CPU core info.
  • Each core object has model, speed, and times properties.
  • Use forEach or loops to access each core's details.
  • Do not modify the returned objects; they represent a snapshot.

Key Takeaways

Use the built-in os module's cpus() method to get CPU info in Node.js.
os.cpus() returns an array with one object per CPU core, each containing model, speed, and times.
Always iterate over the array to access each CPU core's details.
Do not expect a single object or try to modify the returned CPU info.
Import the os module correctly depending on your Node.js environment.