Node.js › Clustering & Worker Threads

What is the os.cpus() function used for when setting up clustering in a Node.js application?

Beginner

Answer

os.cpus() returns an array with one entry per logical CPU core available to the process -- its length is commonly used to decide how many workers to fork, letting code automatically scale its worker count to whatever hardware it runs on rather than hardcoding a fixed number.
console.log(os.cpus().length);
for (let i = 0; i < os.cpus().length; i++) cluster.fork();
Real-world example A startup script forks exactly as many workers as os.cpus().length reports, meaning the same code correctly utilizes all cores whether on a 2-core dev VM or a 32-core production server.

Common follow-ups: How does os.cpus().length behave inside a container with CPU limits below the host's core count?;What's a scenario where you'd deliberately fork fewer workers than the available core count?