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
- Core methods of the
osmodule: Retrieve information such as CPU, memory, hostname, and platform - Core attributes of the
processmodule:argv,env,exit,cwd, etc. - Standard stream operations: stdin / stdout / stderr
- When
process.nextTick()Runs and Its Purpose - Environment Variable Management: .env Files and the dotenv Library
- Practical Tips for Building Cross-Platform CLI Tools
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
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}%`);
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
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()}`);
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
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()}`);
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
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})`);
}
}
}
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.
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
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);
node cli.js --env production --port 8080 --verbose
{ 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
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}`);
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
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`);
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
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);
});
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
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');
});
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
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'));
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:
NODE_ENV=production
DATABASE_URL=postgresql://db.example.com:5432/myapp
APP_SECRET=my-super-secret-key
APP_PORT=3000
Load in the code:
require('dotenv').config();
console.log(`Environment: ${process.env.NODE_ENV}`);
console.log(`Database: ${process.env.DATABASE_URL}`);
console.log(`Port: ${process.env.APP_PORT}`);
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
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 });
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
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);
node syscheck.js --envKeys NODE_ENV,APP_PORT,DATABASE_URL
================================================
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
os.freemem() return?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.process.exit() be used with caution?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.process.nextTick() and setImmediate()?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.config({ path: 'custom/path' }). Be sure to add .env to .gitignore to prevent sensitive information from being exposed.📖 Summary
- The
osmodule provides system-level information: CPU, memory, platform, network interfaces, user information, and more. - process.argv parses the command-line arguments; argv[0] is the Node path, and argv[1] is the script path
process.envmanages environment variables; thedotenvlibrary loads configurations from.envfiles- Use
process.exit()with caution to avoid skipping cleanup logic. process.nextTick()is a microtask and takes precedence oversetImmediateandPromise- Use os.EOL, os.sep, and path.join to handle cross-platform differences
📝 Exercises
- Write a script that outputs the number of CPU cores, total memory (GB), available memory (GB), and memory usage percentage on the current system.
- Use
process.argvto implement a simple command-line calculator that supports three operations:--add,--sub, and--mul. - Create a .env file to store database connection information, load it using dotenv, and read it securely in the script (provide default values)
- Implement a function that checks whether the current platform is Windows; if so, use the
\r\nline break character; otherwise, use\n. - Write a script to monitor memory usage and output a warning message to stderr when it exceeds 90%.