Chapter 26: Node.js OS Module
1. What is the os module?
node:os is a very small but extremely useful built-in module that gives your Node.js program information about the operating system it is running on.
It answers questions like:
- What operating system is this? (Windows, Linux, macOS…)
- How many CPU cores do we have?
- How much RAM is there? How much is free?
- What is the home directory of the current user?
- What is the temporary folder path?
- What user is running this process?
Very important 2025–2026 mindset:
The os module is not used in every file — but when you need it, you really need it.
Typical places where good developers use os:
- Decide behavior based on OS (Windows paths vs Linux paths)
- Decide how many worker threads to spawn (based on CPU cores)
- Log system information on startup (for debugging / monitoring)
- Choose temporary file locations
- Set default data / config / log folders
2. Modern import style (2025–2026)
|
0 1 2 3 4 5 6 7 8 9 |
import os from 'node:os'; // Old style (still works, but not preferred anymore) const os = require('os'); |
Always prefer node:os — clearer in code and better editor support.
3. Most important & frequently used functions
Let’s explore each major method with real examples and comments.
3.1 Basic system information
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
console.log('Platform:', os.platform()); // → 'linux', 'win32', 'darwin' console.log('Operating system:', os.type()); // → 'Linux', 'Windows_NT', 'Darwin' console.log('Architecture:', os.arch()); // → 'x64', 'arm64', 'ia32' console.log('Node was compiled for:', os.arch()); console.log('Hostname:', os.hostname()); // → 'aman-laptop', 'server-01', etc. console.log('Home directory:', os.homedir()); // → '/home/aman' or 'C:\Users\Aman' console.log('Temporary directory:', os.tmpdir()); // → very useful for temp files |
Realistic usage – platform-specific behavior
|
0 1 2 3 4 5 6 7 8 9 10 11 |
const isWindows = os.platform() === 'win32'; const pathSeparator = isWindows ? '\\' : '/'; const logPath = isWindows ? path.join(os.homedir(), 'AppData', 'Local', 'MyApp', 'logs') : path.join(os.homedir(), '.myapp', 'logs'); |
3.2 CPU information – very important for performance
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
console.log('Number of logical CPU cores:', os.cpus().length); // Detailed info about each core const cpus = os.cpus(); console.log('First CPU model:', cpus[0].model); // e.g. "Intel(R) Core(TM) i7-12700H" console.log('CPU speed (MHz):', cpus[0].speed); // Very common pattern: decide worker count const recommendedWorkers = Math.max(1, os.cpus().length - 1); console.log(`Recommended worker threads: {recommendedWorkers}`); |
Real-world decision example
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import { Worker } from 'node:worker_threads'; const workerCount = Math.max(2, Math.floor(os.cpus().length * 0.8)); console.log(`Launching ${workerCount} image processing workers...`); for (let i = 0; i < workerCount; i++) { new Worker('./image-processor.js'); } |
3.3 Memory information – very useful for monitoring & diagnostics
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
console.log('Total system memory:', formatBytes(os.totalmem())); console.log('Free memory:', formatBytes(os.freemem())); // Helper function (very common in logs) function formatBytes(bytes) { const units = ['B', 'KB', 'MB', 'GB', 'TB']; let size = bytes; let unitIndex = 0; while (size >= 1024 && unitIndex < units.length - 1) { size /= 1024; unitIndex++; } return `${size.toFixed(2)} ${units[unitIndex]}`; } |
Typical startup log (very common in production)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
console.log('Server startup environment:'); console.log(` • Node.js: ${process.version}`); console.log(` • Platform: ${os.platform()} (${os.arch()})`); console.log(` • CPUs: ${os.cpus().length} cores`); console.log(` • Memory: ${formatBytes(os.totalmem())} total, ${formatBytes(os.freemem())} free`); console.log(` • Home dir: ${os.homedir()}`); console.log(` • Temp dir: ${os.tmpdir()}`); |
3.4 User & process information
|
0 1 2 3 4 5 6 7 8 9 |
console.log('Current username:', os.userInfo().username); // → 'aman' console.log('User home:', os.userInfo().homedir); console.log('Current UID:', os.userInfo().uid); // Unix only console.log('Current GID:', os.userInfo().gid); // Unix only |
3.5 Network interfaces (sometimes useful)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const interfaces = os.networkInterfaces(); for (const [name, addresses] of Object.entries(interfaces)) { console.log(`Interface: ${name}`); for (const addr of addresses) { if (addr.family === 'IPv4' && !addr.internal) { console.log(` IPv4: ${addr.address}`); } } } |
4. Real-world patterns you’ll see in serious projects (2026)
Pattern 1 – Adaptive worker/thread count
|
0 1 2 3 4 5 6 7 8 |
const WORKER_COUNT = Math.max(2, os.cpus().length - 1); console.log(`Starting ${WORKER_COUNT} background workers...`); |
Pattern 2 – Safe temporary file path
|
0 1 2 3 4 5 6 7 8 9 |
import { tmpdir } from 'node:os'; import { join } from 'node:path'; const tempFile = join(tmpdir(), `upload-${Date.now()}.tmp`); |
Pattern 3 – Platform-specific default folders
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
function getDefaultDataDir() { const home = os.homedir(); if (os.platform() === 'win32') { return join(home, 'AppData', 'Local', 'MyApp'); } if (os.platform() === 'darwin') { return join(home, 'Library', 'Application Support', 'MyApp'); } // Linux & others return join(home, '.myapp'); } |
Pattern 4 – Startup system fingerprint (monitoring / debugging)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function printSystemInfo() { console.log('='.repeat(60)); console.log('System Information'); console.log('='.repeat(60)); console.log(`Platform: ${os.platform()} (${os.arch()})`); console.log(`Release: ${os.release()}`); console.log(`Hostname: ${os.hostname()}`); console.log(`CPUs: ${os.cpus().length} × ${os.cpus()[0].model}`); console.log(`Memory: ${formatBytes(os.totalmem())} total`); console.log(`Free memory: ${formatBytes(os.freemem())}`); console.log('='.repeat(60)); } |
Summary – Quick decision guide 2025–2026
| You need to know… | Use this function / property | Typical use case |
|---|---|---|
| Windows or Linux/macOS? | os.platform() | Path separators, default folders |
| How many CPU cores? | os.cpus().length | Worker threads, parallelism decisions |
| Total & free RAM | os.totalmem() / os.freemem() | Health checks, logging, scaling decisions |
| User’s home directory | os.homedir() | Default config / data location |
| Temporary folder | os.tmpdir() | Safe place for temporary files |
| Current username | os.userInfo().username | Logging, audit trails |
| Network interfaces / IP | os.networkInterfaces() | Microservices, service discovery (rare) |
Which part of the os module would you like to explore much deeper next?
- How to choose optimal worker/thread count using os.cpus()
- Platform-specific default paths for config, logs, cache
- Using os.tmpdir() safely with cleanup
- Monitoring memory usage over time in production
- Complete startup diagnostic log example using os
Just tell me which direction feels most useful right now — I’ll continue with detailed, production-ready examples. 😊
