In this tutorial, you will learn how to get the number of CPU cores in Node.js.
How to Get the Number of System CPU Cores using Node js
Here are steps:
Step 1: Set Up a Node.js Project
First of all, open your terminal or cmd and run the following command into it to SET UP new node js project into your system:
mkdir get-cpu-cores
cd get-cpu-cores
npm init -y
Step 2: Create Server.js File
Next, open your node js project in any text editor. And create a new JavaScript file, for example, server.js
.
Step 3: Import the os module
When you create server.js
or index.js
file into your node js project, then import os module into it to get CPU cores information:
// index.js
const os = require('os');
function getCPUCores() {
const numCPUs = os.cpus().length;
console.log(`Number of CPU Cores: ${numCPUs}`);
}
getCPUCores();
Step 4: Run Your Node.js Script
Now, you can run your script to get the number of CPU cores:
node server.js
Step 5: Get the Result in the Console Screen
You will see the following output in your browser console screen:
Number of CPU Cores: 4
Conclusion
That’s it; you have learned how to get the number of CPU cores in Node.js.