Node Js Get Total Number of System CPU Cores Tutorial
In this short tutorial, we will share the quick and straightforward way to get the total number of computer’s processors through the Node js application using the os module.
To get the computer’s CPU information, we will use the cpus() method; the cpus method returns an array that holds the information about the total numbers of available processors of the system.
Node makes web development eloquently effortless through its handy packages. In this guide, we will discuss the os module, Which stands for the operating system.
It provides practical methods that help you pull out information about the computer’s operating system.
You will be given all the imperative steps that will enhance your knowledge about the node app development. To obtain the total number of system’s processors you must follow all the provided steps.
How to Get System CPU Cores or Processors Available in Node Js
- Step 1: Generate Project Folder
- Step 2: Initialize NPM
- Step 3: Create Main File
- Step 4: Get Computer’s CPU Information
- Step 5: Display Result on Console
Generate Project Folder
In the initial step, you have to create a new project folder.
You can use the given command, hence open the terminal, enter the command and hit enter.
mkdir node-tuts
Now, quickly get inside the project folder.
cd node-tuts
Initialize NPM
We need to set up the package.json file for our node project. Make sure to use the npm initializer command from the console.
npm init
This file stores the project-related metadata, scripts, commands, and additional modules information.
Create Main File
Now, in this step, we need to generated a brand new app.js file.
Ensure that you add the file name into the scripts section, therefore open the package.json file and insert the following code within the file.
...
...
"scripts": {
"start": "node app.js"
},
...
...
Get Computer’s CPU Information
Now, we are utterly ready to write the code to show you how many CPUs exists in your system.
Get into the app.js and place the following code into the file.
const os = require('os');
const cpuCores = os.cpus();
// Display system cpu cores
console.log(cpuCores);
console.log(cpuCores.length);
Display Result on Console
Finally, we are going to show you information about the system’s CPUs and its total numbers.
Head over to console again, type the provided command.
node app.js
Here is the output of my system, this result will be diffrent for you in conjunction with your computer.
Conclusion
We have finally unveiled how to get the system’s cpu information and the total numbers of processors using the os module in the node js application.
I hope this quick guide will help you.