Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

OS Module in Node.js

Learn how to use the Node.js OS module to retrieve operating-system information, including the platform, architecture, CPU details, free memory, total memory, hostname, home directory and uptime. Understand each method through practical programs and outputs.

1. What Is the OS Module?

The OS module is a built-in Node.js module that provides information about the operating system on which a Node.js application is running.

For example, an application may need to know whether it is running on Windows or Linux, how much memory is available, or which CPU architecture the computer uses. The OS module provides methods to retrieve this information.

Example

JavaScript - app.js
const os = require("node:os");

console.log("Operating System:", os.platform());
console.log("Architecture:", os.arch());

Example Output on Windows

Output
Operating System: win32
Architecture: x64

Explanation: The require("node:os") statement loads the built-in OS module. The os.platform() method returns the operating-system platform identifier, while os.arch() returns the CPU architecture for which the Node.js binary was compiled.

Definition: The OS module provides methods to retrieve operating-system and hardware-related information from a Node.js application.

2. Why Do We Use the OS Module?

Applications sometimes need information about the computer where they are running. The OS module helps developers retrieve that information without manually checking system settings.

  • Platform Information: Identify the operating-system platform.
  • Architecture: Retrieve the CPU architecture reported by Node.js.
  • Memory Information: Check total and free system memory.
  • CPU Information: Retrieve information about available CPU cores.
  • System Details: Get the hostname and operating-system information.
  • Uptime: Find how long the system has been running.

3. How the OS Module Works

A Node.js program imports the OS module and calls its methods. The methods return information about the current system, which the program can display or use in its logic.

Step 1: Node.js Application

Create a JavaScript file such as app.js.

↓
Step 2: Import OS Module

Load the built-in module using require("node:os").

↓
Step 3: Call OS Methods

Retrieve platform, memory, CPU and system information.

↓
Step 4: Use the Results

Display the information or use it in application logic.

4. Importing the OS Module

The OS module is included with Node.js, so you do not need to install an additional package to use it.

Program

JavaScript - app.js
const os = require("node:os");

console.log("OS module loaded successfully.");

Output

Output
OS module loaded successfully.

Explanation: The variable os holds the exported methods of the OS module. We can access these methods using dot notation, such as os.platform() and os.totalmem().

5. Understanding os.platform()

The os.platform() method returns a string identifying the operating-system platform for which Node.js was compiled.

Program

JavaScript
const os = require("node:os");

console.log("Platform:", os.platform());

Example Output on Windows

Output
Platform: win32

Explanation: On Windows, this method commonly returns win32, including on 64-bit Windows systems. Other platforms return identifiers such as linux or darwin for macOS.

6. Understanding os.arch()

The os.arch() method returns the CPU architecture for which the current Node.js executable was compiled.

Program

JavaScript
const os = require("node:os");

console.log("Architecture:", os.arch());

Example Output

Output
Architecture: x64

Explanation: The output x64 indicates a 64-bit x86 architecture for the Node.js executable. Other possible values include arm64, depending on the system and Node.js build.

7. Understanding os.hostname()

The os.hostname() method returns the hostname of the operating system. The hostname identifies the computer on a network or within the system environment.

Program

JavaScript
const os = require("node:os");

console.log("Hostname:", os.hostname());

Example Output

Output
Hostname: TRAINING-PC

Explanation: TRAINING-PC is only an illustrative hostname. Your actual output will depend on the name configured for your computer.

8. Understanding os.totalmem() and os.freemem()

The OS module provides methods for retrieving system memory information. os.totalmem() returns the total amount of system memory in bytes, while os.freemem() returns the amount of free system memory in bytes.

Program

JavaScript - app.js
const os = require("node:os");

const totalMemory = os.totalmem();
const freeMemory = os.freemem();

console.log(
    "Total Memory:",
    (totalMemory / (1024 ** 3)).toFixed(2),
    "GB"
);

console.log(
    "Free Memory:",
    (freeMemory / (1024 ** 3)).toFixed(2),
    "GB"
);

Illustrative Output

Output
Total Memory: 16.00 GB
Free Memory: 5.25 GB

Explanation:

  • os.totalmem() returns total system memory in bytes.
  • os.freemem() returns free system memory in bytes.
  • Dividing by 1024 ** 3 converts bytes into gibibytes, commonly displayed as GB in simple examples.
  • toFixed(2) formats the number to two decimal places.
Remember: Memory values change depending on your computer and what applications are currently running. The output above is only an example.

9. Understanding os.cpus()

The os.cpus() method returns an array containing information about each logical CPU core. Each entry includes information such as the CPU model, speed, and time spent in different CPU states.

Program

JavaScript
const os = require("node:os");

const cpus = os.cpus();

console.log("Logical CPU Cores:", cpus.length);
console.log("CPU Model:", cpus[0].model);
console.log("CPU Speed:", cpus[0].speed, "MHz");

Illustrative Output

Output
Logical CPU Cores: 8
CPU Model: Example Processor
CPU Speed: 2400 MHz

Explanation: The os.cpus() method returns an array. The length property tells us how many logical CPU entries are returned. The first entry can be accessed using cpus[0].

The exact CPU model, number of logical cores, and reported speed vary by computer. On unusual or virtualized systems, check that the array contains entries before accessing cpus[0].

10. Understanding os.homedir()

The os.homedir() method returns the home directory of the current user according to the operating system.

Program

JavaScript
const os = require("node:os");

console.log("Home Directory:", os.homedir());

Illustrative Output on Windows

Output
Home Directory: C:\Users\Student

Explanation: The example shows a Windows-style home directory. Your actual output will contain the home directory configured for the current user.

11. Understanding os.uptime()

The os.uptime() method returns the system uptime in seconds. It indicates how long the operating system has been running since its last start.

Program

JavaScript
const os = require("node:os");

const uptimeSeconds = os.uptime();
const uptimeHours = (uptimeSeconds / 3600).toFixed(2);

console.log("System Uptime:", uptimeHours, "hours");

Illustrative Output

Output
System Uptime: 12.50 hours

Explanation: The uptime value is returned in seconds. Dividing the value by 3600 converts seconds into hours. The displayed output depends on the current system uptime.

12. Understanding os.type() and os.release()

The os.type() method returns the operating-system name, while os.release() returns the operating-system release identifier.

Program

JavaScript
const os = require("node:os");

console.log("OS Type:", os.type());
console.log("OS Release:", os.release());

Illustrative Output

Output
OS Type: Windows_NT
OS Release: 10.0.XXXXX

Explanation: The values depend on the operating system and its version. The release shown above is illustrative, not a guaranteed value for every Windows computer.

13. Comparing Important OS Methods

Method Purpose Return Information
os.platform() Identifies the Node.js platform. String such as win32
os.arch() Identifies the Node.js CPU architecture. String such as x64
os.hostname() Returns the computer hostname. String
os.totalmem() Returns total system memory. Number of bytes
os.freemem() Returns free system memory. Number of bytes
os.cpus() Returns logical CPU information. Array of CPU information objects
os.homedir() Returns the current user's home directory. String path
os.uptime() Returns system uptime. Seconds
os.type() Returns the operating-system name. String
os.release() Returns the operating-system release. String

14. OS Information Categories

The OS module groups useful system information into categories. The following diagram shows some examples.

Node.js OS Module

Provides operating-system information.

↓
Platform Details

platform()
type()
release()

Hardware Details

arch()
cpus()

Memory Details

totalmem()
freemem()

System Details

hostname()
homedir()
uptime()

15. Practical Program: Display System Information

Let us combine several OS methods in one program. This program displays the platform, architecture, hostname, total memory, free memory, CPU count and uptime.

Complete Program

JavaScript - app.js
const os = require("node:os");

console.log("Operating System:", os.platform());
console.log("Architecture:", os.arch());
console.log("Hostname:", os.hostname());

console.log(
    "Total Memory:",
    (os.totalmem() / (1024 ** 3)).toFixed(2),
    "GB"
);

console.log(
    "Free Memory:",
    (os.freemem() / (1024 ** 3)).toFixed(2),
    "GB"
);

console.log("Logical CPU Cores:", os.cpus().length);

console.log(
    "System Uptime:",
    (os.uptime() / 3600).toFixed(2),
    "hours"
);

Illustrative Output

Output
Operating System: win32
Architecture: x64
Hostname: TRAINING-PC
Total Memory: 16.00 GB
Free Memory: 5.25 GB
Logical CPU Cores: 8
System Uptime: 12.50 hours

Detailed Explanation:

  • os.platform() identifies the operating-system platform.
  • os.arch() returns the architecture of the Node.js executable.
  • os.hostname() returns the computer's hostname.
  • os.totalmem() and os.freemem() provide memory information in bytes.
  • os.cpus().length counts the logical CPU entries.
  • os.uptime() returns seconds, which the program converts into hours.
Note: The output values above are examples. When you run this program, Node.js displays information from your own computer.

16. How to Run the Program

  1. Create a folder named OSModuleExample.
  2. Create a file named app.js inside that folder.
  3. Paste the complete system-information program into the file.
  4. Open a terminal in the project folder.
  5. Run the program using the Node.js command.

Terminal Command

Terminal
node app.js

Node.js executes the JavaScript file, calls the OS methods, and displays the system information in the terminal.

17. Common Mistakes

Mistake Correct Approach
Trying to install the OS module separately. Import the built-in module using require("node:os").
Assuming every computer returns the same hostname. Remember that the hostname depends on the current system.
Displaying memory bytes as if they were GB. Convert bytes before displaying a human-readable value.
Assuming CPU count is always the same. Use os.cpus().length to inspect the current system.
Assuming uptime is already measured in hours. Remember that os.uptime() returns seconds.
Expecting the same platform identifier everywhere. Platform identifiers depend on the operating system.

18. Practice Tasks

Task 1: Display Platform Information

Write a program that displays the operating-system platform, OS type, OS release, and CPU architecture.

Task 2: Display Memory Information

Write a program that displays total memory and free memory in GB, formatted to two decimal places.

Hint: Use os.totalmem(), os.freemem(), and toFixed(2).

Task 3: Create a System Report

Create a program that displays the hostname, home directory, logical CPU count, and system uptime in hours.

Important Points

  • The OS module is built into Node.js.
  • Use require("node:os") to import it in CommonJS.
  • os.platform() identifies the platform.
  • os.arch() returns the architecture of the Node.js executable.
  • os.totalmem() and os.freemem() return memory values in bytes.
  • os.cpus() returns an array of logical CPU information.
  • os.homedir() returns the current user's home directory.
  • Hostname, memory, CPU information and uptime vary by system.

Summary

The Node.js OS module provides useful information about the operating system and hardware. The os.platform() and os.arch() methods identify the platform and Node.js architecture, while os.hostname() returns the computer's hostname. The os.totalmem() and os.freemem() methods provide memory information in bytes, os.cpus() returns logical CPU details, os.homedir() returns the current user's home directory, and os.uptime() reports system uptime in seconds. These methods help developers inspect system information and build applications that can respond to their runtime environment.