When you are working with Node.js applications it can be helpful in various situations to know how many CPU cores your computer has. This information becomes valuable when you want to make your programs run faster, manage computer resources more efficiently, or handle multiple tasks at the same time. Essentially, understanding the number of CPU cores helps you fine-tune your applications for better performance and responsiveness.
In this tutorial, you will learn how to get the number of CPU cores in Node.js.
How to Get Number of System CPU Cores using Node js
Using the following steps, you can get number of system cpu cores in node js:
- Step 1: Set Up a Node.js Project
- Step 2: Create Server.js File
- Step 3: Import the os module
- Step 4: Run Your Node.js Script
- Step 5: Get Result in Console Screen
Step 1: Set Up a Node.js Project
First of all, open your terminal or cmd and run the following command into it to setup 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
Once you have created server.js or index.js file into your node js project. Next, you need to 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 Result in Console Screen
Once you have run your node js project. The following output will in your 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.