Node.js: OS and Process Modules

Last updated: 2026-08-26

Alice is a DevOps engineer responsible for managing dozens of servers. Every time she deploys a new application, she has to manually log in to the servers to check the value of CPU cores, available memory, and operating system version, and then switch configurations based on environment variables. During an emergency deployment at 3 a.m. one day, she missed a memory shortage issue during her manual checks, causing the deployment to fail. So she decided to write an automated detection script in Node.js to retrieve server resource and environment information with a single click, ensuring future deployments would run smoothly.

1. What You'll Learn



2. The os Module: Collecting System Information

(1) CPU and Memory Information

os.cpus() returns an array of CPU core details; os.totalmem() and os.freemem() return total memory and available memory, respectively (in bytes).

▶ Example: Checking the server's CPU and memory

JAVASCRIPT
const os = require('os');

const cpus = os.cpus();
console.log(`CPU Number of cores: ${cpus.length}`);
console.log(`CPU Model: ${cpus[0].model}`);

const totalMem = os.totalmem();
const freeMem = os.freemem();
const usedPercent = ((totalMem - freeMem) / totalMem * 100).toFixed(1);

console.log(`Total Memory: ${(totalMem / 1024 / 1024 / 1024).toFixed(2)} GB`);
console.log(`Available memory: ${(freeMem / 1024 / 1024 / 1024).toFixed(2)} GB`);
console.log(`Memory Usage: ${usedPercent}%`);
▶ Try it Yourself
TEXT 📖 Display only
CPU Number of cores: 8
CPU Model: Intel(R) Core(TM) i7-9700K CPU @ 3.60GHz
Total Memory: 15.88 GB
Available memory: 6.23 GB
Memory Usage: 60.7%

(2) Operating System Identifier

os.platform() returns the platform identifier (e.g., win32, linux, darwin); os.type() returns the operating system name; os.arch() returns the CPU architecture; and os.hostname() returns the hostname.

▶ Example: Retrieving Operating System Information

JAVASCRIPT
const os = require('os');

console.log(`Platform: ${os.platform()}`);
console.log(`System Type: ${os.type()}`);
console.log(`CPU Architecture: ${os.arch()}`);
console.log(`Hostname: ${os.hostname()}`);
console.log(`System Version: ${os.version()}`);
▶ Try it Yourself
TEXT 📖 Display only
Platform: linux
System Type: Linux
CPU Architecture: x64
Hostname: web-server-01
System Version: #1 SMP Thu Jan 1 00:00:00 UTC 2026

(3) User and Directory Information

os.userInfo() Returns the current user's information; os.homedir() returns the user's home directory; os.tmpdir() returns the temporary file directory.

▶ Example: Retrieving User and Directory Information

JAVASCRIPT
const os = require('os');

const userInfo = os.userInfo();
console.log(`Username: ${userInfo.username}`);
console.log(`Home Directory: ${os.homedir()}`);
console.log(`Shell: ${userInfo.shell}`);
console.log(`Temporary Directory: ${os.tmpdir()}`);
▶ Try it Yourself
TEXT 📖 Display only
Username: alice
Home Directory: /home/alice
Shell: /bin/bash
Temporary Directory: /tmp

(4) Network Interface Information

os.networkInterfaces() Returns detailed information about all network interfaces, including IP addresses, MAC addresses, and address families.

▶ Example: Viewing Network Interfaces

JAVASCRIPT
const os = require('os');

const interfaces = os.networkInterfaces();
for (const [name, addrs] of Object.entries(interfaces)) {
  for (const addr of addrs) {
    if (addr.family === 'IPv4' && !addr.internal) {
      console.log(`${name}: ${addr.address} (${addr.family})`);
    }
  }
}
▶ Try it Yourself
TEXT 📖 Display only
eth0: 192.168.1.100 (IPv4)
wlan0: 10.0.0.5 (IPv4)

(5) Quick Reference for Common OS Methods

Method Return Type Purpose
os.cpus() object[] CPU Core Information Array
os.totalmem() value Total Memory (bytes)
os.freemem() value Available Memory (bytes)
os.platform() string Platform identifier (win32/linux/darwin)
os.type() string Operating System Name
os.arch() string CPU architecture (x64/arm64)
os.hostname() string hostname
os.userInfo() object Current User Information
os.homedir() string User home directory path
os.tmpdir() string Temporary file directory path
os.networkInterfaces() object Network Interface Information
os.uptime() value System uptime (seconds)
os.loadavg() value[] Average System Load (1/5/15 minutes)
os.EOL string Line Break Constant
os.devNull string Empty device path


3. The process module: Process control

(1) Command-line argument process.argv

process.argv is an array; argv[0] is the path to the Node.js executable; argv[1] is the path to the script being executed; and the subsequent elements are the command-line arguments passed in.

100%
flowchart TD
    A["Command-Line Input<br/>node app.js --env prod --port 3000"] --> B["process.argv Array"]
    B --> C["argv[0]: Node.js Path<br/>/usr/local/bin/node"]
    B --> D["argv[1]: Script Path<br/>/home/alice/app.js"]
    B --> E["argv[2]: --env"]
    B --> F["argv[3]: prod"]
    B --> G["argv[4]: --port"]
    B --> H["argv[5]: 3000"]
    E --> I["Parameter Parsing Logic"]
    G --> I
    I --> J["{ env: 'prod', port: '3000' }"]

▶ Example: Parsing Command-Line Arguments

JAVASCRIPT
function parseArgs(argv) {
  const args = {};
  for (let i = 2; i < argv.length; i++) {
    if (argv[i].startsWith('--')) {
      const key = argv[i].slice(2);
      const value = argv[i + 1] && !argv[i + 1].startsWith('--')
        ? argv[++i]
        : true;
      args[key] = value;
    }
  }
  return args;
}

const config = parseArgs(process.argv);
console.log(config);
▶ Try it Yourself
BASH
node cli.js --env production --port 8080 --verbose
TEXT 📖 Display only
{ env: 'production', port: '8080', verbose: true }

(2) The process.env environment variable

process.env Contains all environment variable key-value pairs and serves as the core basis for the deployment script to determine the runtime environment.

▶ Example: Reading and Setting Environment Variables

JAVASCRIPT
console.log(`NODE_ENV: ${process.env.NODE_ENV || 'development'}`);
console.log(`PATH: ${process.env.PATH}`);

process.env.APP_MODE = 'production';
console.log(`APP_MODE: ${process.env.APP_MODE}`);
▶ Try it Yourself
TEXT 📖 Display only
NODE_ENV: development
PATH: /usr/local/bin:/usr/bin:/bin
APP_MODE: production

(3) Process Termination and the Working Directory

process.exit(code) Terminate the process (0 indicates success; non-zero indicates failure), process.cwd() Return to the current working directory.

▶ Example: Conditional Exit and Directory Check

JAVASCRIPT
const requiredEnv = ['DATABASE_URL', 'APP_SECRET'];
const missing = requiredEnv.filter(key => !process.env[key]);

if (missing.length > 0) {
  console.error(`Missing required environment variables: ${missing.join(', ')}`);
  process.exit(1);
}

console.log(`Working Directory: ${process.cwd()}`);
console.log(`Process ID: ${process.pid}`);
console.log(`Runtime: ${process.uptime().toFixed(0)} seconds`);
▶ Try it Yourself
TEXT 📖 Display only
Missing required environment variables: DATABASE_URL, APP_SECRET

(4) Standard streams: stdin / stdout / stderr

process.stdout and process.stderr are writable streams, while process.stdin is a readable stream used for interacting with the terminal.

▶ Example: Using Standard Input and Output

JAVASCRIPT
process.stdout.write('Please enter your name: ');

process.stdin.once('data', (data) => {
  const name = data.toString().trim();
  process.stdout.write(`Hello, ${name}!\n`);
  process.exit(0);
});
▶ Try it Yourself
TEXT 📖 Display only
Please enter your name: Alice
Hello, Alice!

(5) process.nextTick()

process.nextTick() Places the callback in the microtask queue, where it is executed after the current operation is complete but before any I/O events occur. This is often used to ensure that asynchronous operations proceed in the expected order.

▶ Example: Execution Order of nextTick

JAVASCRIPT
console.log('1 - Synchronize Code');

process.nextTick(() => {
  console.log('3 - nextTick callback');
});

console.log('2 - Synchronize Code');

setImmediate(() => {
  console.log('5 - setImmediate');
});

Promise.resolve().then(() => {
  console.log('4 - Promise then');
});
▶ Try it Yourself
TEXT 📖 Display only
1 - Synchronize Code
2 - Synchronize Code
3 - nextTick callback
4 - Promise then
5 - setImmediate

(6) Quick Reference for Common Process Properties and Methods

Property/Method Type Purpose
process.argv string[] Command-line argument array
process.env object Environment Variable Object
process.exit(code) Method Terminate Process
process.cwd() Method Return to the current working directory
process.pid number Current Process ID
process.uptime() Method Process Runtime (seconds)
process.stdin ReadStream Standard input stream
process.stdout WriteStream Standard output stream
process.stderr WriteStream Standard error stream
process.nextTick(cb) Method Microtask Scheduling
process.platform string Operating Platform
process.version string Node.js version
process.versions object Component Version Information
process.kill(pid) Method Send a signal to a process
process.title string Process Title


4. Cross-Platform Constants and Path Handling

(1) Line Breaks and Path Separators

Line breaks and path separators vary across operating systems, so hard-coding them can lead to cross-platform issues.

▶ Example: Using os.EOL and os.sep

JAVASCRIPT
const os = require('os');
const path = require('path');

const lines = ['First line', 'Second line', 'Third line'].join(os.EOL);
console.log('Escaping Line Breaks:', JSON.stringify(os.EOL));
console.log('Path separator:', os.sep);
console.log('path.join Results:', path.join('src', 'utils', 'index.js'));
▶ Try it Yourself
TEXT 📖 Display only
Escaping Line Breaks: "\n"
Path separator: /
path.join Results: src/utils/index.js

(2) Comparison of Cross-Platform Paths and Line Break Constants

Constant Windows Value POSIX Value Purpose
os.EOL \r\n \n line terminator
os.sep \ / path separator
path.sep \ / Path separator (path module)
os.devNull nul /dev/null Empty device path
path.delimiter ; : PATH environment variable separator


5. Environment Variable Management: .env and dotenv

(1) Basic Usage of the dotenv Library

dotenv Loading environment variables from the .env file into process.env is the industry-standard approach for managing project configurations.

▶ Example: Using dotenv to load a .env file

Create the .env file:

TEXT 📖 Display only
NODE_ENV=production
DATABASE_URL=postgresql://db.example.com:5432/myapp
APP_SECRET=my-super-secret-key
APP_PORT=3000

Load in the code:

JAVASCRIPT
require('dotenv').config();

console.log(`Environment: ${process.env.NODE_ENV}`);
console.log(`Database: ${process.env.DATABASE_URL}`);
console.log(`Port: ${process.env.APP_PORT}`);
TEXT 📖 Display only
Environment: production
Database: postgresql://db.example.com:5432/myapp
Port: 3000

(2) Comparison of Methods for Setting Environment Variables

Method Scope Persistence Use Cases
Shell Temporary Settings (export KEY=val) Current Terminal Session Disappears When Session Ends Temporary Debugging
.env File + dotenv Current Node process File persistence Project development
System Environment Variables Global User/System Permanent Server Deployment
Docker ENV / env-file Inside the container Container lifecycle Containerized deployment
CI/CD Platform Setup CI/CD Pipeline Within the Pipeline Continuous Integration

(3) Safely Reading Environment Variables

▶ Example: Reading Environment Variables with Validation

JAVASCRIPT
function getEnv(key, options = {}) {
  const value = process.env[key];

  if (value === undefined) {
    if (options.required) {
      throw new Error(`Environment Variables ${key} It is necessary`);
    }
    return options.default ?? null;
  }

  if (options.type === 'number') {
    const num = Number(value);
    if (isNaN(num)) throw new Error(`Environment Variables ${key} It must be a number`);
    return num;
  }

  if (options.type === 'boolean') {
    return value === 'true' || value === '1';
  }

  return value;
}

const port = getEnv('APP_PORT', { default: 3000, type: 'number' });
const debug = getEnv('DEBUG', { default: false, type: 'boolean' });
const dbUrl = getEnv('DATABASE_URL', { required: true });
▶ Try it Yourself

6. Comprehensive Example: System Diagnostics CLI Tool

Build a complete CLI tool: detect OS/memory/CPU → read environment variables → format the output report.

▶ Example: syscheck.js

JAVASCRIPT 📖 Display only
const os = require('os');

function parseArgs(argv) {
  const args = {};
  for (let i = 2; i < argv.length; i++) {
    if (argv[i].startsWith('--')) {
      const key = argv[i].slice(2);
      const value = argv[i + 1] && !argv[i + 1].startsWith('--')
        ? argv[++i] : true;
      args[key] = value;
    }
  }
  return args;
}

function formatBytes(bytes) {
  const units = ['B', 'KB', 'MB', 'GB'];
  let i = 0;
  let size = bytes;
  while (size >= 1024 && i < units.length - 1) {
    size /= 1024;
    i++;
  }
  return `${size.toFixed(2)} ${units[i]}`;
}

function getSystemInfo() {
  const cpus = os.cpus();
  const totalMem = os.totalmem();
  const freeMem = os.freemem();
  return {
    hostname: os.hostname(),
    platform: os.platform(),
    arch: os.arch(),
    osType: os.type(),
    cpuModel: cpus[0].model,
    cpuCores: cpus.length,
    totalMemory: formatBytes(totalMem),
    freeMemory: formatBytes(freeMem),
    memUsage: ((totalMem - freeMem) / totalMem * 100).toFixed(1) + '%',
    uptime: (os.uptime() / 3600).toFixed(1) + ' hours'
  };
}

function getEnvInfo(keys) {
  const result = {};
  for (const key of keys) {
    result[key] = process.env[key] || '(Not set)';
  }
  return result;
}

function printReport(sys, env) {
  const sep = '='.repeat(48);
  console.log(`\n${sep}`);
  console.log('  System Diagnostic Report');
  console.log(`${sep}`);
  console.log(`  Hostname     : ${sys.hostname}`);
  console.log(`  Platform       : ${sys.platform} / ${sys.arch}`);
  console.log(`  Operating System   : ${sys.osType}`);
  console.log(`  CPU        : ${sys.cpuModel}`);
  console.log(`  CPU Number of cores : ${sys.cpuCores}`);
  console.log(`  Total Memory     : ${sys.totalMemory}`);
  console.log(`  Available memory   : ${sys.freeMemory}`);
  console.log(`  Memory Usage : ${sys.memUsage}`);
  console.log(`  Runtime   : ${sys.uptime}`);
  console.log(`${sep}`);
  console.log('  Environment Variables');
  console.log('-'.repeat(48));
  for (const [key, val] of Object.entries(env)) {
    console.log(`  ${key.padEnd(20)} : ${val}`);
  }
  console.log(`${sep}\n`);
}

const args = parseArgs(process.argv);
const envKeys = args.envKeys
  ? args.envKeys.split(',')
  : ['NODE_ENV', 'HOME', 'PATH', 'SHELL'];
const sys = getSystemInfo();
const env = getEnvInfo(envKeys);
printReport(sys, env);
76 logic lines (exceeds 40-line limit, display only)
BASH
node syscheck.js --envKeys NODE_ENV,APP_PORT,DATABASE_URL
TEXT 📖 Display only
================================================
  System Diagnostic Report
================================================
  Hostname     : web-server-01
  Platform       : linux / x64
  Operating System   : Linux
  CPU        : Intel(R) Xeon(R) CPU E5-2680 v4
  CPU Number of cores : 8
  Total Memory     : 15.88 GB
  Available memory   : 6.23 GB
  Memory Usage : 60.7%
  Runtime   : 72.5 hours
================================================
  Environment Variables
------------------------------------------------
  NODE_ENV             : production
  APP_PORT             : (Not set)
  DATABASE_URL         : (Not set)
================================================

❓ FAQ

Q What are process.argv[0] and process.argv[1], respectively?
A argv[0] is the path to the Node.js executable (e.g., /usr/local/bin/node), and argv[1] is the path to the script file being executed (e.g., /home/alice/app.js). The actual user-provided arguments start at argv[2].
Q How can I safely read environment variables?
A Always provide a default value or check for the variable's existence; convert and validate numeric types; use dotenv to manage the .env file; and never commit the .env file to version control.
Q What units does os.freemem() return?
A It returns the number of bytes. To display the result in GB, you must manually divide by 1073741824 (i.e., 1024 × 1024 × 1024), or you can use a formatting function to automatically convert the value.
Q How do I read user input in Node.js?
A You can use the process.stdin read stream in conjunction with a data event listener, or use the line-by-line reading interface provided by the readline module; readline is better suited for interactive Q&A scenarios.
Q Why should process.exit() be used with caution?
A process.exit() immediately terminates the process, skipping all pending callbacks, I/O operations, and cleanup logic, which may result in data loss or unreleased resources. You should prioritize allowing the event loop to end naturally.
Q What is the difference between process.nextTick() and setImmediate()?
A The nextTick callback is in the microtask queue; it executes immediately after the current operation and takes precedence over all I/O operations. setImmediate is in the macrotask queue and executes during the I/O event loop phase; nextTick has higher priority.
Q Where should the .env file for dotenv be placed?
A By default, it is placed in the project root directory. You can specify a path using config({ path: 'custom/path' }). Be sure to add .env to .gitignore to prevent sensitive information from being exposed.

📖 Summary


📝 Exercises

  1. Write a script that outputs the number of CPU cores, total memory (GB), available memory (GB), and memory usage percentage on the current system.
  2. Use process.argv to implement a simple command-line calculator that supports three operations: --add, --sub, and --mul.
  3. Create a .env file to store database connection information, load it using dotenv, and read it securely in the script (provide default values)
  4. Implement a function that checks whether the current platform is Windows; if so, use the \r\n line break character; otherwise, use \n.
  5. Write a script to monitor memory usage and output a warning message to stderr when it exceeds 90%.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏