Node Js Get Number of System CPU Cores Example

Node Js Get Number of System CPU Cores Example

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.

https://youtu.be/Ujb2dHw2WJY

Recommended Node js Tutorials

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *