Performance: os module for system information
Using the os module affects server-side performance by retrieving system info without blocking the event loop significantly.
Jump into concepts and practice - no test required
const os = require('os'); let cachedSystemInfo = null; function getSystemInfo() { if (!cachedSystemInfo) { cachedSystemInfo = { cpus: os.cpus(), mem: os.totalmem(), freeMem: os.freemem() }; } return cachedSystemInfo; }
const os = require('os'); function getSystemInfo() { const cpus = os.cpus(); const mem = os.totalmem(); const freeMem = os.freemem(); // called repeatedly in a tight loop for(let i=0; i<10000; i++) { os.cpus(); } return { cpus, mem, freeMem }; }
| Pattern | CPU Usage | Event Loop Blocking | Memory Usage | Verdict |
|---|---|---|---|---|
| Repeated os calls in loop | High CPU usage | Blocks event loop for ms | Normal | [X] Bad |
| Cached os info retrieval | Low CPU usage | Minimal event loop blocking | Slightly higher memory for cache | [OK] Good |
os module primarily provide?os moduleos module in Node.js is designed to provide details about the operating system and hardware, such as CPU info, memory, and platform.os module.os module in Node.js?const module = require('module-name');.const os = require('os');
console.log(os.cpus().length);os.cpus() methodos.cpus() method returns an array of objects, each representing a CPU core.const os = require('os');
console.log(os.totalmem());os.totalmem() all lowercase, so spelling is correct.os.totalmem() correctly with parentheses, so no syntax error.totalmem is not a function, should be totalMem claims totalMem is correct, but Node.js uses totalmem lowercase. So totalmem is not a function, should be totalMem is incorrect.os module. Which code snippet correctly does this?os.freemem() returns free memory, and os.totalmem() returns total memory.toFixed(2) to show two decimals. const os = require('os');
const free = os.freemem();
const total = os.totalmem();
console.log(`Free memory: ${(free / total * 100).toFixed(2)}%`); does this correctly.