diff --git a/CHANGELOG.md b/CHANGELOG.md index 757e0af..c80de7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -90,6 +90,7 @@ For major (breaking) changes - **version 4, 3 and 2** - see end of page. | Version | Date | Comment | | ------- | ---------- | --------------------------------------------------------------------------------------------------- | +| 5.28.1 | 2025-12-26 | `networkInterface()` fix secondary and link-local ip (linux, macOS) | | 5.28.0 | 2025-12-25 | `cpuTemperature()` added suppurt for macos-temperature-sensor (macOS) | | 5.27.17 | 2025-12-24 | `graphics()` fix nvidia-smi candidateDir (windows) | | 5.27.16 | 2025-12-23 | `cpuTemperature()` fix sensors parsingg AMD (linux) | diff --git a/docs/history.html b/docs/history.html index 9218d16..8a28626 100644 --- a/docs/history.html +++ b/docs/history.html @@ -57,6 +57,11 @@ + + 5.28.1 + 2025-12-26 + networkInterface() fix secondary and link-local ip (linux, macOS) + 5.28.0 2025-12-25 diff --git a/docs/index.html b/docs/index.html index 2b09ef5..ca3be4c 100644 --- a/docs/index.html +++ b/docs/index.html @@ -170,7 +170,7 @@
systeminformation
 
-
New Version: 5.28.0
+
New Version: 5.28.1
@@ -204,7 +204,7 @@
-
19,496
+
19,547
Lines of code
diff --git a/lib/graphics.js b/lib/graphics.js index 12483cc..ed3c672 100644 --- a/lib/graphics.js +++ b/lib/graphics.js @@ -779,7 +779,7 @@ function graphics(callback) { try { stdout = execSync( 'defaults read /Library/Preferences/com.apple.windowserver.plist 2>/dev/null;defaults read /Library/Preferences/com.apple.windowserver.displays.plist 2>/dev/null; echo ""', - { maxBuffer: 1024 * 20000 } + { maxBuffer: 1024 * 102400 } ); const output = (stdout || '').toString(); const obj = util.plistReader(output); diff --git a/lib/network.js b/lib/network.js index d8eeb21..4be2d6d 100644 --- a/lib/network.js +++ b/lib/network.js @@ -524,12 +524,12 @@ function parseLinesDarwinNics(sections) { function getDarwinNics() { const cmd = '/sbin/ifconfig -v'; try { - const lines = execSync(cmd, { maxBuffer: 1024 * 20000 }) + const lines = execSync(cmd, { maxBuffer: 1024 * 102400 }) .toString() .split('\n'); const nsections = splitSectionsNics(lines); return parseLinesDarwinNics(nsections); - } catch (e) { + } catch { return []; } } @@ -543,7 +543,7 @@ function getLinuxIfaceConnectionName(interfaceName) { const connectionNameLines = resultFormat.split(' ').slice(3); const connectionName = connectionNameLines.join(' '); return connectionName !== '--' ? connectionName : ''; - } catch (e) { + } catch { return ''; } } @@ -566,7 +566,7 @@ function checkLinuxDCHPInterfaces(file) { result = result.concat(checkLinuxDCHPInterfaces(file)); } }); - } catch (e) { + } catch { util.noop(); } return result; @@ -580,12 +580,12 @@ function getLinuxDHCPNics() { const lines = execSync(cmd, util.execOptsLinux).toString().split('\n'); const nsections = splitSectionsNics(lines); result = parseLinuxDHCPNics(nsections); - } catch (e) { + } catch { util.noop(); } try { result = checkLinuxDCHPInterfaces('/etc/network/interfaces'); - } catch (e) { + } catch { util.noop(); } return result; @@ -632,7 +632,7 @@ function getLinuxIfaceDHCPstatus(iface, connectionName, DHCPNics) { break; } return result; - } catch (e) { + } catch { return DHCPNics.indexOf(iface) >= 0; } } else { @@ -648,7 +648,7 @@ function getDarwinIfaceDHCPstatus(iface) { if (lines.length && lines[0].startsWith('lease_time')) { result = true; } - } catch (e) { + } catch { util.noop(); } return result; @@ -662,7 +662,7 @@ function getLinuxIfaceDNSsuffix(connectionName) { const resultFormat = result.replace(/\s+/g, ' ').trim(); const dnsSuffix = resultFormat.split(' ').slice(1).toString(); return dnsSuffix === '--' ? 'Not defined' : dnsSuffix; - } catch (e) { + } catch { return 'Unknown'; } } else { @@ -679,7 +679,7 @@ function getLinuxIfaceIEEE8021xAuth(connectionName) { const authenticationProtocol = resultFormat.split(' ').slice(1).toString(); return authenticationProtocol === '--' ? '' : authenticationProtocol; - } catch (e) { + } catch { return 'Not defined'; } } else { @@ -785,16 +785,44 @@ function networkInterfaces(callback, rescan, defaultString) { nics = getDarwinNics(); nics.forEach((nic) => { + let ip4link = ''; + let ip4linksubnet = ''; + let ip6link = ''; + let ip6linksubnet = ''; + nic.ip4 = ''; + nic.ip6 = ''; if ({}.hasOwnProperty.call(ifaces, nic.iface)) { ifaces[nic.iface].forEach((details) => { if (details.family === 'IPv4' || details.family === 4) { - nic.ip4subnet = details.netmask; + if (!nic.ip4 && !nic.ip4.match(/^169.254/i)) { + nic.ip4 = details.address; + nic.ip4subnet = details.netmask; + } + if (nic.ip4.match(/^169.254/i)) { + ip4link = details.address; + ip4linksubnet = details.netmask; + } } if (details.family === 'IPv6' || details.family === 6) { - nic.ip6subnet = details.netmask; + if (!nic.ip6 && !nic.ip6.match(/^fe80::/i)) { + nic.ip6 = details.address; + nic.ip6subnet = details.netmask; + } + if (nic.ip6.match(/^fe80::/i)) { + ip6link = details.address; + ip6linksubnet = details.netmask; + } } }); } + if (!nic.ip4 && ip4link) { + nic.ip4 = ip4link; + nic.ip4subnet = ip4linksubnet; + } + if (!nic.ip6 && ip6link) { + nic.ip6 = ip6link; + nic.ip6subnet = ip6linksubnet; + } let ifaceSanitized = ''; const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(nic.iface); @@ -881,17 +909,14 @@ function networkInterfaces(callback, rescan, defaultString) { const ifaceName = dev; ifaces[dev].forEach((details) => { if (details.family === 'IPv4' || details.family === 4) { - if (ip4.match(/^169.254/i)) { - ip4link = details.address; - ip4linksubnet = details.netmask; - } else if (!ip4) { + if (!ip4 && !ip4.match(/^169.254/i)) { ip4 = details.address; ip4subnet = details.netmask; } - } - if (!ip4 && (details.family === 'IPv4' || details.family === 4)) { - ip4 = details.address; - ip4subnet = details.netmask; + if (ip4.match(/^169.254/i)) { + ip4link = details.address; + ip4linksubnet = details.netmask; + } } if (details.family === 'IPv6' || details.family === 6) { if (!ip6 && !ip6.match(/^fe80::/i)) { @@ -1260,7 +1285,7 @@ function networkStats(ifaces, callback) { ifaces.__proto__.substring = util.stringSubstring; ifaces.__proto__.trim = util.stringTrim; ifaces.__proto__.startsWith = util.stringStartWith; - } catch (e) { + } catch { Object.setPrototypeOf(ifaces, util.stringObj); } @@ -1577,7 +1602,7 @@ function networkConnections(callback) { cmd = 'export LC_ALL=C; netstat -na | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL'; } - exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + exec(cmd, { maxBuffer: 1024 * 102400 }, function (error, stdout) { let lines = stdout.toString().split('\n'); if (!error && (lines.length > 1 || lines[0] !== '')) { lines.forEach(function (line) { @@ -1622,7 +1647,7 @@ function networkConnections(callback) { resolve(result); } else { cmd = 'ss -tunap | grep "ESTAB\\|SYN-SENT\\|SYN-RECV\\|FIN-WAIT1\\|FIN-WAIT2\\|TIME-WAIT\\|CLOSE\\|CLOSE-WAIT\\|LAST-ACK\\|LISTEN\\|CLOSING"'; - exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + exec(cmd, { maxBuffer: 1024 * 102400 }, function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { @@ -1686,9 +1711,9 @@ function networkConnections(callback) { if (_darwin) { let cmd = 'netstat -natvln | head -n2; netstat -natvln | grep "tcp4\\|tcp6\\|udp4\\|udp6"'; const states = 'ESTABLISHED|SYN_SENT|SYN_RECV|FIN_WAIT1|FIN_WAIT_1|FIN_WAIT2|FIN_WAIT_2|TIME_WAIT|CLOSE|CLOSE_WAIT|LAST_ACK|LISTEN|CLOSING|UNKNOWN'.split('|'); - exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + exec(cmd, { maxBuffer: 1024 * 102400 }, function (error, stdout) { if (!error) { - exec('ps -axo pid,command', { maxBuffer: 1024 * 20000 }, function (err2, stdout2) { + exec('ps -axo pid,command', { maxBuffer: 1024 * 102400 }, function (err2, stdout2) { let processes = stdout2.toString().split('\n'); processes = processes.map((line) => { return line.trim().replace(/ +/g, ' '); @@ -1847,7 +1872,7 @@ function networkConnections(callback) { resolve(result); } }); - } catch (e) { + } catch { if (callback) { callback(result); } @@ -1867,7 +1892,7 @@ function networkGatewayDefault(callback) { if (_linux || _freebsd || _openbsd || _netbsd) { let cmd = 'ip route get 1'; try { - exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + exec(cmd, { maxBuffer: 1024 * 102400 }, function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); const line = lines && lines[0] ? lines[0] : ''; @@ -1887,7 +1912,7 @@ function networkGatewayDefault(callback) { resolve(result); } }); - } catch (e) { + } catch { if (callback) { callback(result); } @@ -1897,7 +1922,7 @@ function networkGatewayDefault(callback) { if (_darwin) { let cmd = 'route -n get default'; try { - exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + exec(cmd, { maxBuffer: 1024 * 102400 }, function (error, stdout) { if (!error) { const lines = stdout .toString() @@ -1907,7 +1932,7 @@ function networkGatewayDefault(callback) { } if (!result) { cmd = "netstat -rn | awk '/default/ {print $2}'"; - exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + exec(cmd, { maxBuffer: 1024 * 102400 }, function (error, stdout) { const lines = stdout .toString() .split('\n') @@ -1927,7 +1952,7 @@ function networkGatewayDefault(callback) { resolve(result); } }); - } catch (e) { + } catch { if (callback) { callback(result); } @@ -1979,7 +2004,7 @@ function networkGatewayDefault(callback) { resolve(result); } }); - } catch (e) { + } catch { if (callback) { callback(result); } diff --git a/lib/processes.js b/lib/processes.js index 15418e6..e369aaa 100644 --- a/lib/processes.js +++ b/lib/processes.js @@ -23,13 +23,13 @@ const util = require('./util'); let _platform = process.platform; -const _linux = (_platform === 'linux' || _platform === 'android'); -const _darwin = (_platform === 'darwin'); -const _windows = (_platform === 'win32'); -const _freebsd = (_platform === 'freebsd'); -const _openbsd = (_platform === 'openbsd'); -const _netbsd = (_platform === 'netbsd'); -const _sunos = (_platform === 'sunos'); +const _linux = _platform === 'linux' || _platform === 'android'; +const _darwin = _platform === 'darwin'; +const _windows = _platform === 'win32'; +const _freebsd = _platform === 'freebsd'; +const _openbsd = _platform === 'openbsd'; +const _netbsd = _platform === 'netbsd'; +const _sunos = _platform === 'sunos'; const _processes_cpu = { all: 0, @@ -57,16 +57,16 @@ const _process_cpu = { }; const _winStatusValues = { - '0': 'unknown', - '1': 'other', - '2': 'ready', - '3': 'running', - '4': 'blocked', - '5': 'suspended blocked', - '6': 'suspended ready', - '7': 'terminated', - '8': 'stopped', - '9': 'growing', + 0: 'unknown', + 1: 'other', + 2: 'ready', + 3: 'running', + 4: 'blocked', + 5: 'suspended blocked', + 6: 'suspended ready', + 7: 'terminated', + 8: 'stopped', + 9: 'growing' }; function parseTimeUnix(time) { @@ -91,7 +91,7 @@ function parseElapsedTime(etime) { const hours = timeStr.length === 3 ? parseInt(timeStr[0] || 0) : 0; const mins = parseInt(timeStr[timeStr.length === 3 ? 1 : 0] || 0); const secs = parseInt(timeStr[timeStr.length === 3 ? 2 : 1] || 0); - const ms = (((((days * 24 + hours) * 60) + mins) * 60 + secs) * 1000); + const ms = (((days * 24 + hours) * 60 + mins) * 60 + secs) * 1000; let res = new Date(current.getTime()); let result = res.toISOString().substring(0, 10) + ' ' + res.toISOString().substring(11, 19); @@ -110,7 +110,6 @@ function parseElapsedTime(etime) { // this function gives an array back, if the services are running. function services(srv, callback) { - // fallback - if only callback is given if (util.isFunction(srv) && !callback) { callback = srv; @@ -120,7 +119,9 @@ function services(srv, callback) { return new Promise((resolve) => { process.nextTick(() => { if (typeof srv !== 'string') { - if (callback) { callback([]); } + if (callback) { + callback([]); + } return resolve([]); } @@ -201,11 +202,14 @@ function services(srv, callback) { } } } - if ((_darwin) && srvString === '*') { // service enumeration not yet suported on mac OS - if (callback) { callback(result); } + if (_darwin && srvString === '*') { + // service enumeration not yet suported on mac OS + if (callback) { + callback(result); + } resolve(result); } - let args = (_darwin) ? ['-caxo', 'pcpu,pmem,pid,command'] : ['-axo', 'pcpu,pmem,pid,command']; + let args = _darwin ? ['-caxo', 'pcpu,pmem,pid,command'] : ['-axo', 'pcpu,pmem,pid,command']; if (srvString !== '' && srvs.length > 0) { util.execSafe('ps', args).then((stdout) => { if (stdout) { @@ -214,12 +218,17 @@ function services(srv, callback) { let ps; if (_darwin) { ps = lines.filter(function (e) { - return (e.toLowerCase().indexOf(srv) !== -1); + return e.toLowerCase().indexOf(srv) !== -1; }); - } else { ps = lines.filter(function (e) { - return (e.toLowerCase().indexOf(' ' + srv.toLowerCase() + ':') !== -1) || (e.toLowerCase().indexOf('(' + srv.toLowerCase() + ' ') !== -1) || (e.toLowerCase().indexOf('(' + srv.toLowerCase() + ')') !== -1) || (e.toLowerCase().indexOf(' ' + srv.toLowerCase().replace(/[0-9.]/g, '') + ':') !== -1) || (e.toLowerCase().indexOf('/' + srv.toLowerCase()) !== -1); + return ( + e.toLowerCase().indexOf(' ' + srv.toLowerCase() + ':') !== -1 || + e.toLowerCase().indexOf('(' + srv.toLowerCase() + ' ') !== -1 || + e.toLowerCase().indexOf('(' + srv.toLowerCase() + ')') !== -1 || + e.toLowerCase().indexOf(' ' + srv.toLowerCase().replace(/[0-9.]/g, '') + ':') !== -1 || + e.toLowerCase().indexOf('/' + srv.toLowerCase()) !== -1 + ); }); } const pids = []; @@ -234,12 +243,20 @@ function services(srv, callback) { running: ps.length > 0, startmode: '', pids: pids, - cpu: parseFloat((ps.reduce(function (pv, cv) { - return pv + parseFloat(cv.trim().split(' ')[0]); - }, 0)).toFixed(2)), - mem: parseFloat((ps.reduce(function (pv, cv) { - return pv + parseFloat(cv.trim().split(' ')[1]); - }, 0)).toFixed(2)) + cpu: parseFloat( + ps + .reduce(function (pv, cv) { + return pv + parseFloat(cv.trim().split(' ')[0]); + }, 0) + .toFixed(2) + ), + mem: parseFloat( + ps + .reduce(function (pv, cv) { + return pv + parseFloat(cv.trim().split(' ')[1]); + }, 0) + .toFixed(2) + ) }); }); if (_linux) { @@ -247,10 +264,10 @@ function services(srv, callback) { let cmd = 'cat /proc/stat | grep "cpu "'; for (let i in result) { for (let j in result[i].pids) { - cmd += (';cat /proc/' + result[i].pids[j] + '/stat'); + cmd += ';cat /proc/' + result[i].pids[j] + '/stat'; } } - exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + exec(cmd, { maxBuffer: 1024 * 102400 }, function (error, stdout) { let curr_processes = stdout.toString().split('\n'); // first line (all - /proc/stat) @@ -292,11 +309,15 @@ function services(srv, callback) { _services_cpu.list = Object.assign({}, list_new); _services_cpu.ms = Date.now() - _services_cpu.ms; _services_cpu.result = Object.assign({}, result); - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); }); } else { - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } } else { @@ -316,7 +337,9 @@ function services(srv, callback) { mem: 0 }); }); - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } else { srvs.forEach(function (srv) { @@ -328,14 +351,18 @@ function services(srv, callback) { mem: 0 }); }); - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } }); } }); } else { - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } } @@ -364,7 +391,7 @@ function services(srv, callback) { if (srvString === '*' || srvs.indexOf(srvName) >= 0 || srvs.indexOf(srvCaption) >= 0) { result.push({ name: srvName, - running: (started.toLowerCase() === 'true'), + running: started.toLowerCase() === 'true', startmode: startMode, pids: [pid], cpu: 0, @@ -374,14 +401,11 @@ function services(srv, callback) { dataSrv.push(srvCaption); } } - }); if (srvString !== '*') { - let srvsMissing = srvs.filter(function (e) { - return dataSrv.indexOf(e) === -1; - }); - srvsMissing.forEach(function (srvName) { + const srvsMissing = srvs.filter((e) => dataSrv.indexOf(e) === -1); + srvsMissing.forEach((srvName) => { result.push({ name: srvName, running: false, @@ -392,10 +416,12 @@ function services(srv, callback) { }); }); } - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } else { - srvs.forEach(function (srvName) { + srvs.forEach((srvName) => { result.push({ name: srvName, running: false, @@ -404,17 +430,23 @@ function services(srv, callback) { mem: 0 }); }); - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } }); - } catch (e) { - if (callback) { callback(result); } + } catch { + if (callback) { + callback(result); + } resolve(result); } } } else { - if (callback) { callback([]); } + if (callback) { + callback([]); + } resolve([]); } }); @@ -424,17 +456,17 @@ function services(srv, callback) { exports.services = services; function parseProcStat(line) { - let parts = line.replace(/ +/g, ' ').split(' '); - let user = (parts.length >= 2 ? parseInt(parts[1]) : 0); - let nice = (parts.length >= 3 ? parseInt(parts[2]) : 0); - let system = (parts.length >= 4 ? parseInt(parts[3]) : 0); - let idle = (parts.length >= 5 ? parseInt(parts[4]) : 0); - let iowait = (parts.length >= 6 ? parseInt(parts[5]) : 0); - let irq = (parts.length >= 7 ? parseInt(parts[6]) : 0); - let softirq = (parts.length >= 8 ? parseInt(parts[7]) : 0); - let steal = (parts.length >= 9 ? parseInt(parts[8]) : 0); - let guest = (parts.length >= 10 ? parseInt(parts[9]) : 0); - let guest_nice = (parts.length >= 11 ? parseInt(parts[10]) : 0); + const parts = line.replace(/ +/g, ' ').split(' '); + const user = parts.length >= 2 ? parseInt(parts[1]) : 0; + const nice = parts.length >= 3 ? parseInt(parts[2]) : 0; + const system = parts.length >= 4 ? parseInt(parts[3]) : 0; + const idle = parts.length >= 5 ? parseInt(parts[4]) : 0; + const iowait = parts.length >= 6 ? parseInt(parts[5]) : 0; + const irq = parts.length >= 7 ? parseInt(parts[6]) : 0; + const softirq = parts.length >= 8 ? parseInt(parts[7]) : 0; + const steal = parts.length >= 9 ? parseInt(parts[8]) : 0; + const guest = parts.length >= 10 ? parseInt(parts[9]) : 0; + const guest_nice = parts.length >= 11 ? parseInt(parts[10]) : 0; return user + nice + system + idle + iowait + irq + softirq + steal + guest + guest_nice; } @@ -453,11 +485,11 @@ function calcProcStatLinux(line, all, _cpu_old) { let cpuu = 0; let cpus = 0; if (_cpu_old.all > 0 && _cpu_old.list[pid]) { - cpuu = (utime + cutime - _cpu_old.list[pid].utime - _cpu_old.list[pid].cutime) / (all - _cpu_old.all) * 100; // user - cpus = (stime + cstime - _cpu_old.list[pid].stime - _cpu_old.list[pid].cstime) / (all - _cpu_old.all) * 100; // system + cpuu = ((utime + cutime - _cpu_old.list[pid].utime - _cpu_old.list[pid].cutime) / (all - _cpu_old.all)) * 100; // user + cpus = ((stime + cstime - _cpu_old.list[pid].stime - _cpu_old.list[pid].cstime) / (all - _cpu_old.all)) * 100; // system } else { - cpuu = (utime + cutime) / (all) * 100; // user - cpus = (stime + cstime) / (all) * 100; // system + cpuu = ((utime + cutime) / all) * 100; // user + cpus = ((stime + cstime) / all) * 100; // system } return { pid: pid, @@ -497,11 +529,11 @@ function calcProcStatWin(procStat, all, _cpu_old) { let cpuu = 0; let cpus = 0; if (_cpu_old.all > 0 && _cpu_old.list[procStat.pid]) { - cpuu = (procStat.utime - _cpu_old.list[procStat.pid].utime) / (all - _cpu_old.all) * 100; // user - cpus = (procStat.stime - _cpu_old.list[procStat.pid].stime) / (all - _cpu_old.all) * 100; // system + cpuu = ((procStat.utime - _cpu_old.list[procStat.pid].utime) / (all - _cpu_old.all)) * 100; // user + cpus = ((procStat.stime - _cpu_old.list[procStat.pid].stime) / (all - _cpu_old.all)) * 100; // system } else { - cpuu = (procStat.utime) / (all) * 100; // user - cpus = (procStat.stime) / (all) * 100; // system + cpuu = (procStat.utime / all) * 100; // user + cpus = (procStat.stime / all) * 100; // system } return { pid: procStat.pid, @@ -512,13 +544,10 @@ function calcProcStatWin(procStat, all, _cpu_old) { }; } - - // -------------------------- // running processes function processes(callback) { - let parsedhead = []; function getName(command) { @@ -539,7 +568,6 @@ function processes(callback) { } function parseLine(line) { - let offset = 0; let offset2 = 0; @@ -569,13 +597,32 @@ function processes(callback) { checkColumn(7); const nice = parseInt(line.substring(parsedhead[7].from + offset, parsedhead[7].to + offset2)) || 0; checkColumn(8); - const started = !_sunos ? parseElapsedTime(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim()) : parseTimeUnix(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim()); + const started = !_sunos + ? parseElapsedTime(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim()) + : parseTimeUnix(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim()); checkColumn(9); let state = line.substring(parsedhead[9].from + offset, parsedhead[9].to + offset2).trim(); - state = (state[0] === 'R' ? 'running' : (state[0] === 'S' ? 'sleeping' : (state[0] === 'T' ? 'stopped' : (state[0] === 'W' ? 'paging' : (state[0] === 'X' ? 'dead' : (state[0] === 'Z' ? 'zombie' : ((state[0] === 'D' || state[0] === 'U') ? 'blocked' : 'unknown'))))))); + state = + state[0] === 'R' + ? 'running' + : state[0] === 'S' + ? 'sleeping' + : state[0] === 'T' + ? 'stopped' + : state[0] === 'W' + ? 'paging' + : state[0] === 'X' + ? 'dead' + : state[0] === 'Z' + ? 'zombie' + : state[0] === 'D' || state[0] === 'U' + ? 'blocked' + : 'unknown'; checkColumn(10); let tty = line.substring(parsedhead[10].from + offset, parsedhead[10].to + offset2).trim(); - if (tty === '?' || tty === '??') { tty = ''; } + if (tty === '?' || tty === '??') { + tty = ''; + } checkColumn(11); const user = line.substring(parsedhead[11].from + offset, parsedhead[11].to + offset2).trim(); checkColumn(12); @@ -583,9 +630,12 @@ function processes(callback) { let command = ''; let params = ''; let fullcommand = line.substring(parsedhead[12].from + offset, parsedhead[12].to + offset2).trim(); - if (fullcommand.substr(fullcommand.length - 1) === ']') { fullcommand = fullcommand.slice(0, -1); } - if (fullcommand.substr(0, 1) === '[') { command = fullcommand.substring(1); } - else { + if (fullcommand.substr(fullcommand.length - 1) === ']') { + fullcommand = fullcommand.slice(0, -1); + } + if (fullcommand.substr(0, 1) === '[') { + command = fullcommand.substring(1); + } else { const p1 = fullcommand.indexOf('('); const p2 = fullcommand.indexOf(')'); const p3 = fullcommand.indexOf('/'); @@ -601,8 +651,8 @@ function processes(callback) { // try to figure out where parameter starts let firstParamPos = fullcommand.indexOf(' -'); let firstParamPathPos = fullcommand.indexOf(' /'); - firstParamPos = (firstParamPos >= 0 ? firstParamPos : 10000); - firstParamPathPos = (firstParamPathPos >= 0 ? firstParamPathPos : 10000); + firstParamPos = firstParamPos >= 0 ? firstParamPos : 10000; + firstParamPathPos = firstParamPathPos >= 0 ? firstParamPathPos : 10000; const firstPos = Math.min(firstParamPos, firstParamPathPos); let tmpCommand = fullcommand.substr(0, firstPos); const tmpParams = fullcommand.substr(firstPos); @@ -627,10 +677,9 @@ function processes(callback) { } } } - } - return ({ + return { pid: pid, parentPid: ppid, name: _linux ? getName(command) : command, @@ -649,7 +698,7 @@ function processes(callback) { command: command, params: params, path: cmdPath - }); + }; } function parseProcesses(lines) { @@ -658,7 +707,7 @@ function processes(callback) { let head = lines[0]; parsedhead = util.parseHead(head, 8); lines.shift(); - lines.forEach(function (line) { + lines.forEach((line) => { if (line.trim() !== '') { result.push(parseLine(line)); } @@ -667,7 +716,6 @@ function processes(callback) { return result; } function parseProcesses2(lines) { - function formatDateTime(time) { const month = ('0' + (time.getMonth() + 1).toString()).slice(-2); const year = time.getFullYear().toString(); @@ -676,7 +724,7 @@ function processes(callback) { const mins = ('0' + time.getMinutes().toString()).slice(-2); const secs = ('0' + time.getSeconds().toString()).slice(-2); - return (year + '-' + month + '-' + day + ' ' + hours + ':' + mins + ':' + secs); + return year + '-' + month + '-' + day + ' ' + hours + ':' + mins + ':' + secs; } function parseElapsed(etime) { @@ -695,12 +743,12 @@ function processes(callback) { } let result = []; - lines.forEach(function (line) { + lines.forEach((line) => { if (line.trim() !== '') { line = line.trim().replace(/ +/g, ' ').replace(/,+/g, '.'); const parts = line.split(' '); const command = parts.slice(9).join(' '); - const pmem = parseFloat((1.0 * parseInt(parts[3]) * 1024 / os.totalmem()).toFixed(1)); + const pmem = parseFloat(((1.0 * parseInt(parts[3]) * 1024) / os.totalmem()).toFixed(1)); const started = parseElapsed(parts[5]); result.push({ @@ -716,7 +764,22 @@ function processes(callback) { memRss: parseInt(parts[3]), nice: parseInt(parts[4]), started: started, - state: (parts[6] === 'R' ? 'running' : (parts[6] === 'S' ? 'sleeping' : (parts[6] === 'T' ? 'stopped' : (parts[6] === 'W' ? 'paging' : (parts[6] === 'X' ? 'dead' : (parts[6] === 'Z' ? 'zombie' : ((parts[6] === 'D' || parts[6] === 'U') ? 'blocked' : 'unknown'))))))), + state: + parts[6] === 'R' + ? 'running' + : parts[6] === 'S' + ? 'sleeping' + : parts[6] === 'T' + ? 'stopped' + : parts[6] === 'W' + ? 'paging' + : parts[6] === 'X' + ? 'dead' + : parts[6] === 'Z' + ? 'zombie' + : parts[6] === 'D' || parts[6] === 'U' + ? 'blocked' + : 'unknown', tty: parts[7], user: parts[8], command: command @@ -741,223 +804,265 @@ function processes(callback) { if ((_processes_cpu.ms && Date.now() - _processes_cpu.ms >= 500) || _processes_cpu.ms === 0) { if (_linux || _freebsd || _openbsd || _netbsd || _darwin || _sunos) { - if (_linux) { cmd = 'export LC_ALL=C; ps -axo pid:11,ppid:11,pcpu:6,pmem:6,pri:5,vsz:11,rss:11,ni:5,etime:30,state:5,tty:15,user:20,command; unset LC_ALL'; } - if (_freebsd || _openbsd || _netbsd) { cmd = 'export LC_ALL=C; ps -axo pid,ppid,pcpu,pmem,pri,vsz,rss,ni,etime,state,tty,user,command; unset LC_ALL'; } - if (_darwin) { cmd = 'ps -axo pid,ppid,pcpu,pmem,pri,vsz=temp_title_1,rss=temp_title_2,nice,etime=temp_title_3,state,tty,user,command -r'; } - if (_sunos) { cmd = 'ps -Ao pid,ppid,pcpu,pmem,pri,vsz,rss,nice,stime,s,tty,user,comm'; } - exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - if (!error && stdout.toString().trim()) { - result.list = (parseProcesses(stdout.toString().split('\n'))).slice(); - result.all = result.list.length; - result.running = result.list.filter(function (e) { - return e.state === 'running'; - }).length; - result.blocked = result.list.filter(function (e) { - return e.state === 'blocked'; - }).length; - result.sleeping = result.list.filter(function (e) { - return e.state === 'sleeping'; - }).length; + if (_linux) { + cmd = 'export LC_ALL=C; ps -axo pid:11,ppid:11,pcpu:6,pmem:6,pri:5,vsz:11,rss:11,ni:5,etime:30,state:5,tty:15,user:20,command; unset LC_ALL'; + } + if (_freebsd || _openbsd || _netbsd) { + cmd = 'export LC_ALL=C; ps -axo pid,ppid,pcpu,pmem,pri,vsz,rss,ni,etime,state,tty,user,command; unset LC_ALL'; + } + if (_darwin) { + cmd = 'ps -axo pid,ppid,pcpu,pmem,pri,vsz=temp_title_1,rss=temp_title_2,nice,etime=temp_title_3,state,tty,user,command -r'; + } + if (_sunos) { + cmd = 'ps -Ao pid,ppid,pcpu,pmem,pri,vsz,rss,nice,stime,s,tty,user,comm'; + } + try { + exec(cmd, { maxBuffer: 1024 * 102400 }, (error, stdout) => { + if (!error && stdout.toString().trim()) { + result.list = parseProcesses(stdout.toString().split('\n')).slice(); + result.all = result.list.length; + result.running = result.list.filter((e) => { + return e.state === 'running'; + }).length; + result.blocked = result.list.filter((e) => { + return e.state === 'blocked'; + }).length; + result.sleeping = result.list.filter((e) => { + return e.state === 'sleeping'; + }).length; - if (_linux) { - // calc process_cpu - ps is not accurate in linux! - cmd = 'cat /proc/stat | grep "cpu "'; - result.list.forEach((element) => { - cmd += (';cat /proc/' + element.pid + '/stat'); + if (_linux) { + // calc process_cpu - ps is not accurate in linux! + cmd = 'cat /proc/stat | grep "cpu "'; + result.list.forEach((element) => { + cmd += ';cat /proc/' + element.pid + '/stat'; + }); + exec(cmd, { maxBuffer: 1024 * 102400 }, (error, stdout) => { + let curr_processes = stdout.toString().split('\n'); + + // first line (all - /proc/stat) + let all = parseProcStat(curr_processes.shift()); + + // process + let list_new = {}; + let resultProcess = {}; + curr_processes.forEach((element) => { + resultProcess = calcProcStatLinux(element, all, _processes_cpu); + + if (resultProcess.pid) { + // store pcpu in outer array + let listPos = result.list + .map((e) => { + return e.pid; + }) + .indexOf(resultProcess.pid); + if (listPos >= 0) { + result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus; + result.list[listPos].cpuu = resultProcess.cpuu; + result.list[listPos].cpus = resultProcess.cpus; + } + + // save new values + list_new[resultProcess.pid] = { + cpuu: resultProcess.cpuu, + cpus: resultProcess.cpus, + utime: resultProcess.utime, + stime: resultProcess.stime, + cutime: resultProcess.cutime, + cstime: resultProcess.cstime + }; + } + }); + + // store old values + _processes_cpu.all = all; + _processes_cpu.list = Object.assign({}, list_new); + _processes_cpu.ms = Date.now() - _processes_cpu.ms; + _processes_cpu.result = Object.assign({}, result); + if (callback) { + callback(result); + } + resolve(result); + }); + } else { + if (callback) { + callback(result); + } + resolve(result); + } + } else { + cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,stat,tty,user,comm'; + if (_sunos) { + cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,s,tty,user,comm'; + } + exec(cmd, { maxBuffer: 1024 * 102400 }, (error, stdout) => { + if (!error) { + let lines = stdout.toString().split('\n'); + lines.shift(); + + result.list = parseProcesses2(lines).slice(); + result.all = result.list.length; + result.running = result.list.filter((e) => { + return e.state === 'running'; + }).length; + result.blocked = result.list.filter((e) => { + return e.state === 'blocked'; + }).length; + result.sleeping = result.list.filter((e) => { + return e.state === 'sleeping'; + }).length; + if (callback) { + callback(result); + } + resolve(result); + } else { + if (callback) { + callback(result); + } + resolve(result); + } }); - exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - let curr_processes = stdout.toString().split('\n'); - - // first line (all - /proc/stat) - let all = parseProcStat(curr_processes.shift()); - - // process + } + }); + } catch { + if (callback) { + callback(result); + } + resolve(result); + } + } else if (_windows) { + try { + util + .powerShell( + 'Get-CimInstance Win32_Process | select-Object ProcessId,ParentProcessId,ExecutionState,Caption,CommandLine,ExecutablePath,UserModeTime,KernelModeTime,WorkingSetSize,Priority,PageFileUsage, @{n="CreationDate";e={$_.CreationDate.ToString("yyyy-MM-dd HH:mm:ss")}} | fl' + ) + .then((stdout, error) => { + if (!error) { + let processSections = stdout.split(/\n\s*\n/); + let procs = []; + let procStats = []; let list_new = {}; - let resultProcess = {}; - curr_processes.forEach((element) => { - resultProcess = calcProcStatLinux(element, all, _processes_cpu); - - if (resultProcess.pid) { - - // store pcpu in outer array - let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid); - if (listPos >= 0) { - result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus; - result.list[listPos].cpuu = resultProcess.cpuu; - result.list[listPos].cpus = resultProcess.cpus; + let allcpuu = 0; + let allcpus = 0; + processSections.forEach((element) => { + if (element.trim() !== '') { + let lines = element.trim().split('\r\n'); + let pid = parseInt(util.getValue(lines, 'ProcessId', ':', true), 10); + let parentPid = parseInt(util.getValue(lines, 'ParentProcessId', ':', true), 10); + let statusValue = util.getValue(lines, 'ExecutionState', ':'); + let name = util.getValue(lines, 'Caption', ':', true); + let commandLine = util.getValue(lines, 'CommandLine', ':', true); + // get additional command line data + let additionalCommand = false; + lines.forEach((line) => { + if (additionalCommand && line.toLowerCase().startsWith(' ')) { + commandLine += ' ' + line.trim(); + } else { + additionalCommand = false; + } + if (line.toLowerCase().startsWith('commandline')) { + additionalCommand = true; + } + }); + let commandPath = util.getValue(lines, 'ExecutablePath', ':', true); + let utime = parseInt(util.getValue(lines, 'UserModeTime', ':', true), 10); + let stime = parseInt(util.getValue(lines, 'KernelModeTime', ':', true), 10); + let memw = parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10); + allcpuu = allcpuu + utime; + allcpus = allcpus + stime; + result.all++; + if (!statusValue) { + result.unknown++; + } + if (statusValue === '3') { + result.running++; + } + if (statusValue === '4' || statusValue === '5') { + result.blocked++; } - // save new values - list_new[resultProcess.pid] = { - cpuu: resultProcess.cpuu, - cpus: resultProcess.cpus, - utime: resultProcess.utime, - stime: resultProcess.stime, - cutime: resultProcess.cutime, - cstime: resultProcess.cstime - }; + procStats.push({ + pid: pid, + utime: utime, + stime: stime, + cpu: 0, + cpuu: 0, + cpus: 0 + }); + procs.push({ + pid: pid, + parentPid: parentPid, + name: name, + cpu: 0, + cpuu: 0, + cpus: 0, + mem: (memw / os.totalmem()) * 100, + priority: parseInt(util.getValue(lines, 'Priority', ':', true), 10), + memVsz: parseInt(util.getValue(lines, 'PageFileUsage', ':', true), 10), + memRss: Math.floor(parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10) / 1024), + nice: 0, + started: util.getValue(lines, 'CreationDate', ':', true), + state: !statusValue ? _winStatusValues[0] : _winStatusValues[statusValue], + tty: '', + user: '', + command: commandLine || name, + path: commandPath, + params: '' + }); } }); + result.sleeping = result.all - result.running - result.blocked - result.unknown; + result.list = procs; + procStats.forEach((element) => { + let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _processes_cpu); + + // store pcpu in outer array + let listPos = result.list.map((e) => e.pid).indexOf(resultProcess.pid); + if (listPos >= 0) { + result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus; + result.list[listPos].cpuu = resultProcess.cpuu; + result.list[listPos].cpus = resultProcess.cpus; + } + + // save new values + list_new[resultProcess.pid] = { + cpuu: resultProcess.cpuu, + cpus: resultProcess.cpus, + utime: resultProcess.utime, + stime: resultProcess.stime + }; + }); + // store old values - _processes_cpu.all = all; + _processes_cpu.all = allcpuu + allcpus; + _processes_cpu.all_utime = allcpuu; + _processes_cpu.all_stime = allcpus; _processes_cpu.list = Object.assign({}, list_new); _processes_cpu.ms = Date.now() - _processes_cpu.ms; _processes_cpu.result = Object.assign({}, result); - if (callback) { callback(result); } - resolve(result); - }); - } else { - if (callback) { callback(result); } - resolve(result); - } - } else { - cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,stat,tty,user,comm'; - if (_sunos) { - cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,s,tty,user,comm'; - } - exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { - if (!error) { - let lines = stdout.toString().split('\n'); - lines.shift(); - - result.list = parseProcesses2(lines).slice(); - result.all = result.list.length; - result.running = result.list.filter(function (e) { - return e.state === 'running'; - }).length; - result.blocked = result.list.filter(function (e) { - return e.state === 'blocked'; - }).length; - result.sleeping = result.list.filter(function (e) { - return e.state === 'sleeping'; - }).length; - if (callback) { callback(result); } - resolve(result); - } else { - if (callback) { callback(result); } - resolve(result); } + if (callback) { + callback(result); + } + resolve(result); }); + } catch { + if (callback) { + callback(result); } - }); - } else if (_windows) { - try { - util.powerShell('Get-CimInstance Win32_Process | select-Object ProcessId,ParentProcessId,ExecutionState,Caption,CommandLine,ExecutablePath,UserModeTime,KernelModeTime,WorkingSetSize,Priority,PageFileUsage, @{n="CreationDate";e={$_.CreationDate.ToString("yyyy-MM-dd HH:mm:ss")}} | fl').then((stdout, error) => { - if (!error) { - let processSections = stdout.split(/\n\s*\n/); - let procs = []; - let procStats = []; - let list_new = {}; - let allcpuu = 0; - let allcpus = 0; - processSections.forEach((element) => { - if (element.trim() !== '') { - let lines = element.trim().split('\r\n'); - let pid = parseInt(util.getValue(lines, 'ProcessId', ':', true), 10); - let parentPid = parseInt(util.getValue(lines, 'ParentProcessId', ':', true), 10); - let statusValue = util.getValue(lines, 'ExecutionState', ':'); - let name = util.getValue(lines, 'Caption', ':', true); - let commandLine = util.getValue(lines, 'CommandLine', ':', true); - // get additional command line data - let additionalCommand = false; - lines.forEach((line) => { - if (additionalCommand && line.toLowerCase().startsWith(' ')) { - commandLine += ' ' + line.trim(); - } else { - additionalCommand = false; - } - if (line.toLowerCase().startsWith('commandline')) { - additionalCommand = true; - } - }); - let commandPath = util.getValue(lines, 'ExecutablePath', ':', true); - let utime = parseInt(util.getValue(lines, 'UserModeTime', ':', true), 10); - let stime = parseInt(util.getValue(lines, 'KernelModeTime', ':', true), 10); - let memw = parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10); - allcpuu = allcpuu + utime; - allcpus = allcpus + stime; - result.all++; - if (!statusValue) { result.unknown++; } - if (statusValue === '3') { result.running++; } - if (statusValue === '4' || statusValue === '5') { result.blocked++; } - - procStats.push({ - pid: pid, - utime: utime, - stime: stime, - cpu: 0, - cpuu: 0, - cpus: 0, - }); - procs.push({ - pid: pid, - parentPid: parentPid, - name: name, - cpu: 0, - cpuu: 0, - cpus: 0, - mem: memw / os.totalmem() * 100, - priority: parseInt(util.getValue(lines, 'Priority', ':', true), 10), - memVsz: parseInt(util.getValue(lines, 'PageFileUsage', ':', true), 10), - memRss: Math.floor(parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10) / 1024), - nice: 0, - started: util.getValue(lines, 'CreationDate', ':', true), - state: (!statusValue ? _winStatusValues[0] : _winStatusValues[statusValue]), - tty: '', - user: '', - command: commandLine || name, - path: commandPath, - params: '' - }); - } - }); - - result.sleeping = result.all - result.running - result.blocked - result.unknown; - result.list = procs; - procStats.forEach((element) => { - let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _processes_cpu); - - // store pcpu in outer array - let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid); - if (listPos >= 0) { - result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus; - result.list[listPos].cpuu = resultProcess.cpuu; - result.list[listPos].cpus = resultProcess.cpus; - } - - // save new values - list_new[resultProcess.pid] = { - cpuu: resultProcess.cpuu, - cpus: resultProcess.cpus, - utime: resultProcess.utime, - stime: resultProcess.stime - }; - }); - - // store old values - _processes_cpu.all = allcpuu + allcpus; - _processes_cpu.all_utime = allcpuu; - _processes_cpu.all_stime = allcpus; - _processes_cpu.list = Object.assign({}, list_new); - _processes_cpu.ms = Date.now() - _processes_cpu.ms; - _processes_cpu.result = Object.assign({}, result); - } - if (callback) { - callback(result); - } - resolve(result); - }); - } catch (e) { - if (callback) { callback(result); } resolve(result); } } else { - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } } else { - if (callback) { callback(_processes_cpu.result); } + if (callback) { + callback(_processes_cpu.result); + } resolve(_processes_cpu.result); } }); @@ -972,7 +1077,6 @@ exports.processes = processes; // (PID, CPU-Usage %, Mem-Usage %) function processLoad(proc, callback) { - // fallback - if only callback is given if (util.isFunction(proc) && !callback) { callback = proc; @@ -981,11 +1085,12 @@ function processLoad(proc, callback) { return new Promise((resolve) => { process.nextTick(() => { - proc = proc || ''; if (typeof proc !== 'string') { - if (callback) { callback([]); } + if (callback) { + callback([]); + } return resolve([]); } @@ -998,8 +1103,7 @@ function processLoad(proc, callback) { processesString.__proto__.substring = util.stringSubstring; processesString.__proto__.trim = util.stringTrim; processesString.__proto__.startsWith = util.stringStartWith; - - } catch (e) { + } catch { Object.setPrototypeOf(processesString, util.stringObj); } @@ -1022,7 +1126,7 @@ function processLoad(proc, callback) { let processes = processesString.split('|'); let result = []; - const procSanitized = util.isPrototypePolluted() ? '' : (util.sanitizeShellString(proc) || '*'); + const procSanitized = util.isPrototypePolluted() ? '' : util.sanitizeShellString(proc) || '*'; // from here new // let result = { @@ -1066,7 +1170,7 @@ function processLoad(proc, callback) { }); let pname = ''; let inList = false; - processes.forEach(function (proc) { + processes.forEach((proc) => { if (name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) { inList = true; pname = proc; @@ -1075,10 +1179,10 @@ function processLoad(proc, callback) { if (processesString === '*' || inList) { let processFound = false; - result.forEach(function (item) { + result.forEach((item) => { if (item.proc.toLowerCase() === pname.toLowerCase()) { item.pids.push(pid); - item.mem += mem / os.totalmem() * 100; + item.mem += (mem / os.totalmem()) * 100; processFound = true; } }); @@ -1088,7 +1192,7 @@ function processLoad(proc, callback) { pid: pid, pids: [pid], cpu: 0, - mem: mem / os.totalmem() * 100 + mem: (mem / os.totalmem()) * 100 }); } } @@ -1097,11 +1201,8 @@ function processLoad(proc, callback) { // add missing processes if (processesString !== '*') { - let processesMissing = processes.filter(function (name) { - return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0; - - }); - processesMissing.forEach(function (procName) { + let processesMissing = processes.filter((name) => procStats.filter((item) => item.name.toLowerCase().indexOf(name) >= 0).length === 0); + processesMissing.forEach((procName) => { result.push({ proc: procName, pid: null, @@ -1118,7 +1219,9 @@ function processLoad(proc, callback) { let listPos = -1; for (let j = 0; j < result.length; j++) { - if (result[j].pid === resultProcess.pid || result[j].pids.indexOf(resultProcess.pid) >= 0) { listPos = j; } + if (result[j].pid === resultProcess.pid || result[j].pids.indexOf(resultProcess.pid) >= 0) { + listPos = j; + } } if (listPos >= 0) { result[listPos].cpu += resultProcess.cpuu + resultProcess.cpus; @@ -1147,7 +1250,9 @@ function processLoad(proc, callback) { } }); } catch (e) { - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } } @@ -1156,22 +1261,29 @@ function processLoad(proc, callback) { const params = ['-axo', 'pid,ppid,pcpu,pmem,comm']; util.execSafe('ps', params).then((stdout) => { if (stdout) { - let procStats = []; - let lines = stdout.toString().split('\n').filter(function (line) { - if (processesString === '*') { return true; } - if (line.toLowerCase().indexOf('grep') !== -1) { return false; } // remove this?? - let found = false; - processes.forEach(function (item) { - found = found || (line.toLowerCase().indexOf(item.toLowerCase()) >= 0); + const procStats = []; + const lines = stdout + .toString() + .split('\n') + .filter((line) => { + if (processesString === '*') { + return true; + } + if (line.toLowerCase().indexOf('grep') !== -1) { + return false; + } // remove this?? + let found = false; + processes.forEach((item) => { + found = found || line.toLowerCase().indexOf(item.toLowerCase()) >= 0; + }); + return found; }); - return found; - }); lines.shift(); - lines.forEach(function (line) { - let data = line.trim().replace(/ +/g, ' ').split(' '); + lines.forEach((line) => { + const data = line.trim().replace(/ +/g, ' ').split(' '); if (data.length > 4) { const linuxName = data[4].indexOf('/') >= 0 ? data[4].substring(0, data[4].indexOf('/')) : data[4]; - const name = _linux ? (linuxName) : data[4].substring(data[4].lastIndexOf('/') + 1); + const name = _linux ? linuxName : data[4].substring(data[4].lastIndexOf('/') + 1); procStats.push({ name, pid: parseInt(data[0]) || 0, @@ -1182,7 +1294,7 @@ function processLoad(proc, callback) { } }); - procStats.forEach(function (item) { + procStats.forEach((item) => { let listPos = -1; let inList = false; let name = item.name; @@ -1191,14 +1303,13 @@ function processLoad(proc, callback) { listPos = j; } } - processes.forEach(function (proc) { - + processes.forEach((proc) => { if (item.name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) { inList = true; name = proc; } }); - if ((processesString === '*') || inList) { + if (processesString === '*' || inList) { if (listPos < 0) { if (name) { result.push({ @@ -1222,10 +1333,14 @@ function processLoad(proc, callback) { if (processesString !== '*') { // add missing processes - let processesMissing = processes.filter(function (name) { - return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0; + let processesMissing = processes.filter((name) => { + return ( + procStats.filter((item) => { + return item.name.toLowerCase().indexOf(name) >= 0; + }).length === 0 + ); }); - processesMissing.forEach(function (procName) { + processesMissing.forEach((procName) => { result.push({ proc: procName, pid: null, @@ -1237,16 +1352,16 @@ function processLoad(proc, callback) { } if (_linux) { // calc process_cpu - ps is not accurate in linux! - result.forEach(function (item) { + result.forEach((item) => { item.cpu = 0; }); let cmd = 'cat /proc/stat | grep "cpu "'; for (let i in result) { for (let j in result[i].pids) { - cmd += (';cat /proc/' + result[i].pids[j] + '/stat'); + cmd += ';cat /proc/' + result[i].pids[j] + '/stat'; } } - exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) { + exec(cmd, { maxBuffer: 1024 * 102400 }, (error, stdout) => { let curr_processes = stdout.toString().split('\n'); // first line (all - /proc/stat) @@ -1259,7 +1374,6 @@ function processLoad(proc, callback) { resultProcess = calcProcStatLinux(element, all, _process_cpu); if (resultProcess.pid) { - // find result item let resultItemId = -1; for (let i in result) { @@ -1284,7 +1398,7 @@ function processLoad(proc, callback) { } }); - result.forEach(function (item) { + result.forEach((item) => { item.cpu = Math.round(item.cpu * 100) / 100; }); @@ -1292,15 +1406,21 @@ function processLoad(proc, callback) { _process_cpu.list = Object.assign({}, list_new); _process_cpu.ms = Date.now() - _process_cpu.ms; _process_cpu.result = Object.assign({}, result); - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); }); } else { - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } } else { - if (callback) { callback(result); } + if (callback) { + callback(result); + } resolve(result); } }); diff --git a/lib/util.js b/lib/util.js index f8844c2..223c0e4 100644 --- a/lib/util.js +++ b/lib/util.js @@ -51,13 +51,13 @@ const _psIdSeperator = '--##ID##--'; const execOptsWin = { windowsHide: true, - maxBuffer: 1024 * 20000, + maxBuffer: 1024 * 102400, encoding: 'UTF-8', env: Object.assign({}, process.env, { LANG: 'en_US.UTF-8' }) }; const execOptsLinux = { - maxBuffer: 1024 * 20000, + maxBuffer: 1024 * 102400, encoding: 'UTF-8', stdio: ['pipe', 'pipe', 'ignore'] }; @@ -436,7 +436,7 @@ function powerShellStart() { _psChild = spawn(_powerShell, ['-NoProfile', '-NoLogo', '-InputFormat', 'Text', '-NoExit', '-Command', '-'], { stdio: 'pipe', windowsHide: true, - maxBuffer: 1024 * 20000, + maxBuffer: 1024 * 102400, encoding: 'UTF-8', env: Object.assign({}, process.env, { LANG: 'en_US.UTF-8' }) }); @@ -516,7 +516,7 @@ function powerShell(cmd) { const child = spawn(_powerShell, ['-NoProfile', '-NoLogo', '-InputFormat', 'Text', '-ExecutionPolicy', 'Unrestricted', '-Command', cmd], { stdio: 'pipe', windowsHide: true, - maxBuffer: 1024 * 20000, + maxBuffer: 1024 * 102400, encoding: 'UTF-8', env: Object.assign({}, process.env, { LANG: 'en_US.UTF-8' }) });