Skip to main content

Command Palette

Search for a command to run...

13) Node OS Module

Updated
View as Markdown
  1. Introduction
    The os module in Node.js is a core module that provides information about the operating system (OS) your Node application is running on. It helps you write programs that are aware of system-level details like CPU, memory, platform, and more.
    os is a core Node.js module
    Provides system-level information
    Common methods: platform(), arch(), cpus() totalmem(), freemem() hostname(), uptime()
    Used for:
    Performance monitoring
    Scaling apps
    Environment detection

    Why Use the os Module?
    You use it when you need:
    System information (CPU, memory)
    Platform-specific logic
    Performance monitoring
    Debugging or logging environment details

  2. Commonly Used Methods
    i) OS Platform

    console.log(os.platform());
    
    // Output
    // win32
    // linux
    // darwin (Mac)
    

    ii) CPU Architecture

    console.log(os.arch());
    
    // x64, arm
    

    iii) CPU Info

    console.log(os.cpus());
    
    /* Returns array of CPU cores with:
    model
    speed
    times (user, idle, etc.) */
    

    iv) Total Memory

    console.log(os.totalmem());
    
    // in bytes
    

    v) Free Memory

    console.log(os.freemem());
    

    vi) Hostname

    console.log(os.hostname());
    

    vii) OS Type

    console.log(os.type());
    // Linux
    // Windows_NT
    

    viii) Example

    const os = require('os');
    
    console.log('Platform:', os.platform());
    console.log('CPU Arch:', os.arch());
    console.log('Total Memory:', os.totalmem());
    console.log('Free Memory:', os.freemem());
    console.log('CPUs:', os.cpus().length);
    
  3. Real-World Use Cases
    i) Performance Monitoring
    Check memory usage
    CPU load
    ii) Environment Detection

    if (os.platform() === 'win32') {
      console.log('Running on Windows');
    }
    

    iii) Scaling Apps
    Decide number of workers based on CPU cores

    const numCPUs = os.cpus().length;
    

    iv) Logging & Debugging
    Capture system details in logs