### Monitor Multiple Processes Simultaneously Source: https://context7.com/soyuka/pidusage/llms.txt This example shows how to monitor CPU and memory usage for an array of PIDs concurrently. The result is an object keyed by PID, enabling efficient tracking of multiple processes. ```javascript const pidusage = require('pidusage') const { spawn } = require('child_process') async function monitorMultipleProcesses() { // Spawn a child process const child = spawn('node', ['-e', 'setInterval(() => {}, 1000)']) const pids = [process.pid, child.pid] try { const stats = await pidusage(pids) // stats is keyed by PID for (const pid of pids) { console.log(`\nProcess ${pid}:`) console.log(` CPU: ${stats[pid].cpu.toFixed(2)}%`) console.log(` Memory: ${(stats[pid].memory / 1024 / 1024).toFixed(2)} MB`) console.log(` Parent PID: ${stats[pid].ppid}`) console.log(` Elapsed: ${stats[pid].elapsed} ms`) } // Output: // Process 12345: // CPU: 5.20% // Memory: 45.32 MB // Parent PID: 1 // Elapsed: 125000 ms // // Process 12346: // CPU: 0.10% // Memory: 12.50 MB // Parent PID: 12345 // Elapsed: 500 ms } finally { child.kill() } } monitorMultipleProcesses() ``` -------------------------------- ### Get Single Process Stats with Callback Source: https://context7.com/soyuka/pidusage/llms.txt This snippet demonstrates how to fetch CPU and memory statistics for a process using the traditional Node.js error-first callback pattern. Ensure to handle potential errors in the callback. ```javascript const pidusage = require('pidusage') pidusage(process.pid, function (err, stats) { if (err) { console.error('Error:', err.message) return } console.log('CPU Usage:', stats.cpu + '%') console.log('Memory Usage:', (stats.memory / 1024 / 1024).toFixed(2) + ' MB') console.log('Process ID:', stats.pid) console.log('Parent Process ID:', stats.ppid) console.log('Process Uptime:', (stats.elapsed / 1000).toFixed(2) + ' seconds') }) ``` -------------------------------- ### Get Single Process Stats with Async/Await Source: https://context7.com/soyuka/pidusage/llms.txt Use this snippet to retrieve CPU and memory statistics for the current Node.js process using the async/await Promise-based API. It returns an object with detailed process information. ```javascript const pidusage = require('pidusage') // Using async/await async function getProcessStats() { try { const stats = await pidusage(process.pid) console.log(stats) // Output: // { // cpu: 10.0, // percentage (from 0 to 100*vcore) // memory: 357306368, // bytes // ppid: 312, // PPID // pid: 727, // PID // ctime: 867000, // ms user + system time // elapsed: 6650000, // ms since the start of the process // timestamp: 864000000 // ms since epoch // } } catch (err) { console.error('Failed to get process stats:', err.message) } } getProcessStats() ``` -------------------------------- ### Monitor HTTP Server Resource Usage Source: https://context7.com/soyuka/pidusage/llms.txt This snippet demonstrates how to integrate pidusage into an HTTP server to expose resource usage metrics via a health check endpoint. It includes setup for the server, handling the '/health' route, and background monitoring. ```javascript const http = require('http') const pidusage = require('pidusage') const server = http.createServer(async (req, res) => { if (req.url === '/health') { try { const stats = await pidusage(process.pid) res.writeHead(200, { 'Content-Type': 'application/json' }) res.end(JSON.stringify({ status: 'healthy', pid: stats.pid, cpu: stats.cpu.toFixed(2) + '%', memory: (stats.memory / 1024 / 1024).toFixed(2) + ' MB', uptime: Math.floor(stats.elapsed / 1000) + ' seconds' }, null, 2)) } catch (err) { res.writeHead(500, { 'Content-Type': 'application/json' }) res.end(JSON.stringify({ status: 'error', message: err.message })) } } else { res.writeHead(200) res.end('Hello World\n') } }) server.listen(8080, () => { console.log('Server running on http://localhost:8080') console.log('Health check: http://localhost:8080/health') }) // Background monitoring const interval = setInterval(async () => { const stats = await pidusage(process.pid) console.log(`[Monitor] CPU: ${stats.cpu.toFixed(2)}% | Memory: ${(stats.memory / 1024 / 1024).toFixed(2)} MB`) }, 5000) process.on('SIGINT', () => { clearInterval(interval) pidusage.clear() server.close() }) ``` -------------------------------- ### Configure pidusage Options Source: https://context7.com/soyuka/pidusage/llms.txt Demonstrates programmatic configuration and environment variable usage to control process monitoring behavior. ```javascript const pidusage = require('pidusage') // Option 1: Programmatic configuration async function withOptions() { const stats = await pidusage(process.pid, { usePs: true, // Force use of 'ps' command instead of /proc files maxage: 30000 // Keep process history for 30 seconds (default: 60000) }) console.log(stats) } // Option 2: Environment variables (set before requiring pidusage) // PIDUSAGE_USE_PS=true - Use ps command // PIDUSAGE_MAXAGE=30000 - Max age in milliseconds // PIDUSAGE_SILENT=1 - Suppress console messages // Example with callback and options pidusage(process.pid, { usePs: true }, function (err, stats) { if (err) { console.error(err) return } console.log('Stats using ps command:', stats) }) withOptions() ``` -------------------------------- ### Retrieve process statistics Source: https://github.com/soyuka/pidusage/blob/main/README.md Demonstrates fetching CPU and memory usage for a single PID or multiple PIDs using callbacks or promises. ```js var pidusage = require('pidusage') pidusage(process.pid, function (err, stats) { console.log(stats) // => { // cpu: 10.0, // percentage (from 0 to 100*vcore) // memory: 357306368, // bytes // ppid: 312, // PPID // pid: 727, // PID // ctime: 867000, // ms user + system time // elapsed: 6650000, // ms since the start of the process // timestamp: 864000000 // ms since epoch // } cb() }) // It supports also multiple pids pidusage([727, 1234], function (err, stats) { console.log(stats) // => { // 727: { // cpu: 10.0, // percentage (from 0 to 100*vcore) // memory: 357306368, // bytes // ppid: 312, // PPID // pid: 727, // PID // ctime: 867000, // ms user + system time // elapsed: 6650000, // ms since the start of the process // timestamp: 864000000 // ms since epoch // }, // 1234: { // cpu: 0.1, // percentage (from 0 to 100*vcore) // memory: 3846144, // bytes // ppid: 727, // PPID // pid: 1234, // PID // ctime: 0, // ms user + system time // elapsed: 20000, // ms since the start of the process // timestamp: 864000000 // ms since epoch // } // } }) // If no callback is given it returns a promise instead const stats = await pidusage(process.pid) console.log(stats) // => { // cpu: 10.0, // percentage (from 0 to 100*vcore) // memory: 357306368, // bytes // ppid: 312, // PPID // pid: 727, // PID // ctime: 867000, // ms user + system time // elapsed: 6650000, // ms since the start of the process // timestamp: 864000000 // ms since epoch // } // Avoid using setInterval as they could overlap with asynchronous processing function compute(cb) { pidusage(process.pid, function (err, stats) { console.log(stats) // => { // cpu: 10.0, // percentage (from 0 to 100*vcore) // memory: 357306368, // bytes // ppid: 312, // PPID // pid: 727, // PID // ctime: 867000, // ms user + system time // elapsed: 6650000, // ms since the start of the process // timestamp: 864000000 // ms since epoch // } cb() }) } function interval(time) { setTimeout(function() { compute(function() { interval(time) }) }, time) } // Compute statistics every second: interval(1000) // Above example using async/await const compute = async () => { const stats = await pidusage(process.pid) // do something } // Compute statistics every second: const interval = async (time) => { setTimeout(async () => { await compute() interval(time) }, time) } interval(1000) ``` -------------------------------- ### Enable ps command usage Source: https://github.com/soyuka/pidusage/blob/main/README.md Use the usePs option to force the library to use the ps command instead of default procfile parsing. ```javascript pidusage(pid, {usePs: true}) ``` -------------------------------- ### pidusage(pids, [options], [callback]) Source: https://github.com/soyuka/pidusage/blob/main/README.md Retrieves process information for one or more PIDs. It can return a Promise or use a callback. ```APIDOC ## pidusage(pids, [options], [callback]) ### Description Get pid informations. ### Method N/A (Function Call) ### Endpoint N/A (Library Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **pids** (Number | Array | String | Array) - Required - A pid or a list of pids. - **[options]** (Object) - Optional - Options object. See the table below. - **[callback]** (Function) - Optional - Called when the statistics are ready. If not provided a promise is returned instead. ### Options - **[usePs]** (boolean) - Optional - When true uses `ps` instead of proc files to fetch process information. Environment variable: `PIDUSAGE_USE_PS`. Default: `false`. - **[maxage]** (number) - Optional - Max age of a process on history. Environment variable: `PIDUSAGE_MAXAGE`. Default: `60000`. `PIDUSAGE_SILENT=1` can be used to remove every console message triggered by pidusage. ### Request Example ```javascript // Using Promise pidusage('123').then(function (stat) { console.log(stat) }) // Using callback pidusage('123', function (err, stat) { if (err) { // handle error } else { console.log(stat) } }) // With options pidusage('123', { usePs: true }).then(function (stat) { console.log(stat) }) ``` ### Response #### Success Response (200) - **pid** (Number) - The process ID. - **cpu** (Number) - CPU usage percentage. - **memory** (Number) - Memory usage percentage. - **ctime** (Number) - CPU time. - **elapsed** (Number) - Elapsed time since the process started. - **timestamp** (Number) - Timestamp of the measurement. #### Response Example ```json { "pid": 123, "cpu": 10.5, "memory": 20.2, "ctime": 12345, "elapsed": 67890, "timestamp": 1678886400000 } ``` ``` -------------------------------- ### Default pidusage Output Structure Source: https://github.com/soyuka/pidusage/blob/main/CHANGELOG.md The default call to pidusage now returns a more comprehensive data object including CPU, memory, PIDs, and timing information. ```json { "cpu": 10.0, // percentage (it may happen to be greater than 100%) "memory": 357306368, // bytes "ppid": 312, // PPID "pid": 727, // PID "ctime": 867000, // ms user + system time "elapsed": 6650000, // ms since the start of the process "timestamp": 864000000 // ms since epoch } ``` -------------------------------- ### Handle pidusage Errors Source: https://context7.com/soyuka/pidusage/llms.txt Implements error handling for common scenarios like invalid PIDs or missing processes. ```javascript const pidusage = require('pidusage') async function safeMonitor(pid) { try { const stats = await pidusage(pid) return stats } catch (err) { switch (err.message) { case 'One of the pids provided is invalid': console.error(`Invalid PID provided: ${pid}`) break case 'You must provide at least one pid': console.error('No PID was provided') break case 'No matching pid found': console.error(`Process ${pid} does not exist (code: ${err.code})`) break default: console.error('Unexpected error:', err.message) } return null } } // Test error cases async function demonstrateErrors() { await safeMonitor(null) // "One of the pids provided is invalid" await safeMonitor(-1) // "One of the pids provided is invalid" await safeMonitor('invalid') // "One of the pids provided is invalid" await safeMonitor(65535) // "No matching pid found" (likely non-existent) await safeMonitor(process.pid) // Success } demonstrateErrors() ``` -------------------------------- ### Monitor Processes Continuously with JavaScript Source: https://context7.com/soyuka/pidusage/llms.txt Uses recursive setTimeout to prevent overlapping asynchronous calls during periodic process statistics retrieval. ```javascript const pidusage = require('pidusage') function formatBytes(bytes) { if (bytes >= 1073741824) return (bytes / 1073741824).toFixed(2) + ' GB' if (bytes >= 1048576) return (bytes / 1048576).toFixed(2) + ' MB' if (bytes >= 1024) return (bytes / 1024).toFixed(2) + ' KB' return bytes + ' B' } // Monitor process every second using recursive setTimeout async function monitor(pid, intervalMs = 1000) { const compute = async () => { try { const stats = await pidusage(pid) console.log(`[${new Date().toISOString()}] PID ${pid}`) console.log(` CPU: ${stats.cpu.toFixed(2)}%`) console.log(` Memory: ${formatBytes(stats.memory)}`) console.log(` Uptime: ${(stats.elapsed / 1000 / 60).toFixed(2)} minutes`) } catch (err) { console.error('Monitoring error:', err.message) return // Stop monitoring on error } setTimeout(compute, intervalMs) } compute() } // Start monitoring current process monitor(process.pid, 2000) // Handle graceful shutdown process.on('SIGINT', () => { pidusage.clear() process.exit() }) ``` -------------------------------- ### Require pidusage directly (pre v0.1.0) Source: https://github.com/soyuka/pidusage/blob/main/CHANGELOG.md Prior to version 0.1.0, pidusage was required by directly calling the module. ```javascript require('pidusage')(pid, fn) ``` -------------------------------- ### Require pidusage with stat method (v0.1.0) Source: https://github.com/soyuka/pidusage/blob/main/CHANGELOG.md In version 0.1.0, pidusage was required using the .stat method. This version also introduced an 'unmonitor' method. ```javascript require('pidusage').stat(pid, fn) ``` -------------------------------- ### pidusage.clear() Source: https://github.com/soyuka/pidusage/blob/main/README.md Clears all in-memory metrics and the event loop managed by pidusage. ```APIDOC ## pidusage.clear() ### Description If needed this function can be used to delete all in-memory metrics and clear the event loop. This is not necessary before exiting as the interval we're registring does not hold up the event loop. ### Method N/A (Function Call) ### Endpoint N/A (Library Function) ### Parameters None ### Request Example ```javascript pidusage.clear(); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Clear Process History Cache Source: https://context7.com/soyuka/pidusage/llms.txt Uses pidusage.clear() to stop internal timers and reset in-memory metrics, useful for testing or cleanup. ```javascript const pidusage = require('pidusage') async function monitorWithCleanup() { // Perform several measurements for (let i = 0; i < 5; i++) { const stats = await pidusage(process.pid) console.log(`Measurement ${i + 1}: CPU ${stats.cpu.toFixed(2)}%`) await new Promise(resolve => setTimeout(resolve, 500)) } // Clear all cached process history and stop internal timers pidusage.clear() console.log('Process history cleared') } monitorWithCleanup() // Cleanup on process exit (optional - interval auto-cleans) process.on('exit', () => { pidusage.clear() }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.