Topic 36 of 55
Operating (os) Metadata Module
Overview
The `os` module provides operating system-related utility methods and properties. It lets your Node app inspect the hardware it's running on, which is useful for logging, performance tuning (like spawning worker threads), and cross-platform compatibility.
Syntax
javascript
const os = require('os');
console.log("OS Platform:", os.platform()); // 'win32', 'darwin', 'linux'
console.log("OS Architecture:", os.arch()); // 'x64', 'arm64'
console.log("Free Memory (bytes):", os.freemem());
console.log("Total Memory (bytes):", os.totalmem());
console.log("System Uptime (seconds):", os.uptime());
// Get information about the current user
console.log("User Info:", os.userInfo());
// { username: 'kartik', homedir: '/Users/kartik', ... }Common Pitfalls
- `os.cpus().length` returns the number of logical cores (including hyper-threading), not necessarily physical hardware cores.
- `os.freemem()` might return a very low number on Linux systems because Linux aggressively uses free RAM for disk caching. It doesn't mean your app is out of memory.
Real-World Example
Using the OS module to determine the optimal number of Node.js Cluster workers:
example
javascript
const os = require('os');
const cluster = require('cluster');
// Get an array of objects representing every CPU core
const cpus = os.cpus();
const numCores = cpus.length;
if (cluster.isPrimary) {
console.log(`Master process is running. System has ${numCores} cores.`);
// Spawn a worker thread for every CPU core available
for (let i = 0; i < numCores; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died. Restarting...`);
cluster.fork(); // Auto-restart dead workers
});
} else {
// Workers handle the actual workload
require('./server.js');
}