Node.js Reference ยท path, os and url
Node.js os.availableParallelism() method
Reference for os.availableParallelism() in Node.js: the number of CPUs your process may use in parallel, and how to size worker pools safely.
os.availableParallelism() returns a positive integer: the amount of parallelism the program should assume it can use. It is the recommended way to decide how many worker threads, child processes or concurrent tasks to start for CPU-bound work.
Unlike os.cpus().length, it asks the runtime for the number of CPUs the process is actually allowed to run on, so it respects things like CPU affinity. It always returns at least 1.
import os from "node:os"; const workers = os.availableParallelism(); console.log(workers >= 1);
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.availableParallelism(): number
| Name | Description |
|---|---|
| (none) | The function takes no arguments. |
Returns: an integer greater than or equal to 1.
Edge cases: the value can be smaller than the number of CPUs on the machine and can differ between runs when the environment changes (for example when a scheduler pins the process).
Usage notes
- Use it for CPU-bound pools. For I/O-bound work (HTTP requests, file reads) the optimal concurrency is usually unrelated to the CPU count.
- Prefer it over
os.cpus().length. The latter lists logical CPUs of the machine and can be empty in restricted environments. - It does not read container CPU quotas in every setup. If you run under a strict quota, make the pool size configurable, for example from an environment variable.
- Leave headroom. Starting exactly as many busy workers as CPUs leaves nothing for the event loop, garbage collection or other processes.
- Added in Node.js 18.14 and 19.4, so it is available on all current LTS lines.