Open In App

What is the os module in NodeJS used for?

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The OS module in NodeJS provides various utilities related to the operating system. It allows you to retrieve information about the current operating system, network interfaces, system uptime, and more.

What is the OS Module?

The OS module is a built-in module in NodeJS that provides operating system-related functionality. It allows you to access information about the underlying operating system on which the NodeJS application is running.

Why Use the OS Module?

The OS module is useful for tasks that require information about the operating system environment. This can include tasks such as determining the platform on which the application is running, retrieving information about system resources, or working with network interfaces.

How to Use the OS Module:

The OS module provides various functions and properties to access information about the operating system. Some of the commonly used functions and properties include:

  • os.totalmem(): Returns the total amount of system memory in bytes.
  • os.freemem(): Returns the amount of free system memory in bytes.
  • os.cpus(): Returns an array of objects containing information about each CPU/core.
  • os.networkInterfaces(): Returns an object containing information about the network interfaces on the system.
  • os.uptime(): Returns the system uptime in seconds.

Example: In this example, various functions and properties of the os module are used to retrieve information about the operating system, including the platform, architecture, hostname, memory usage, CPU details, network interfaces, and system uptime.

const os = require('os');

console.log('Platform:', os.platform());
console.log('Architecture:', os.arch());
console.log('Hostname:', os.hostname());
console.log('Total Memory:', os.totalmem() / (1024 * 1024), 'MB');
console.log('Free Memory:', os.freemem() / (1024 * 1024), 'MB');
console.log('CPUs:', os.cpus().length);
console.log('Network Interfaces:', os.networkInterfaces());
console.log('Uptime:', os.uptime(), 'seconds');

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads