Node.js Reference ยท path, os and url
Node.js os.cpus() method
Reference for os.cpus() in Node.js: get one object per logical CPU with model, speed and time counters, and learn why it is not a worker-count tool.
os.cpus() returns an array with one object per logical CPU the operating system reports. Each object describes the processor model, its clock speed in MHz and a times object with how many milliseconds that core has spent in user mode, nice mode, system mode, idle and interrupt handling.
The call is synchronous and cheap. It is handy for diagnostics and simple monitoring, but the array length is not always the right number of workers to start: see os.availableParallelism().
import os from "node:os"; const cores = os.cpus(); console.log(cores.length, cores[0].model);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
os.cpus(): Array<{ model: string, speed: number, times: { user: number, nice: number, sys: number, idle: number, irq: number } }>
| Name | Description |
|---|---|
| (none) | The function takes no arguments. |
Returns: an array of objects, one per logical CPU. model is a descriptive string, speed is the clock in MHz, and every field of times is a cumulative number of milliseconds since boot.
Edge cases: on some platforms (certain containers, restricted sandboxes and some ARM systems) the array can be empty or speed can be 0. Never assume cpus()[0] exists in code that must run everywhere.
Usage notes
- Counters are cumulative. A single reading says little. Take two snapshots and subtract them, as in the second example, to get utilization over an interval.
niceis always0on Windows. The field exists but the platform has no equivalent.- Logical CPUs, not physical cores. With hyper-threading you see each hardware thread.
- Not a limit-aware count. Inside a container with a CPU quota,
os.cpus().lengthstill reports the host's CPUs. Useos.availableParallelism()to size a worker pool. - Not stable output. Model strings and speeds differ per machine, so never put them in tests or cache keys.
- The data is a copy. Mutating the returned objects does not affect anything.