From 23f5a66be25971df81351605d35750eb5700333b Mon Sep 17 00:00:00 2001 From: Sebastian Hildebrandt Date: Thu, 2 Nov 2017 10:01:28 +0100 Subject: [PATCH] code cleanup, AMD cpu base frequencies table --- .gitignore | 3 +- CHANGELOG.md | 3 +- lib/battery.js | 37 ++++--- lib/cpu.js | 256 +++++++++++++++++++++++++++++--------------- lib/docker.js | 52 ++++----- lib/dockerSocket.js | 26 ++--- lib/filesystem.js | 97 +++++++++-------- lib/graphics.js | 74 ++++++------- lib/index.js | 19 ++-- lib/internet.js | 32 +++--- lib/memory.js | 77 +++++++------ lib/network.js | 105 +++++++++--------- lib/osinfo.js | 99 ++++++++--------- lib/processes.js | 124 +++++++++++---------- lib/system.js | 40 ++++--- lib/users.js | 60 +++++------ lib/util.js | 10 +- 17 files changed, 581 insertions(+), 533 deletions(-) diff --git a/.gitignore b/.gitignore index 4e3cd3a..58e00ab 100644 --- a/.gitignore +++ b/.gitignore @@ -56,4 +56,5 @@ npm* .*.swp .svn .hg -CVS \ No newline at end of file +CVS +.eslintrc.json \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 45b6156..9c20c89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -99,7 +99,8 @@ Other changes | Version | Date | Comment | | -------------- | -------------- | -------- | -| 3.32.2 | 2017-10-23 | bugfix JSON.parse error `blockDevices()` | +| 3.32.3 | 2017-11-02 | code cleanup, AMD cpu base frequencies table | +| 3.32.2 | 2017-11-01 | bugfix JSON.parse error `blockDevices()` | | 3.32.1 | 2017-10-23 | updated docs | | 3.32.0 | 2017-10-23 | extended `memLayout()` - added manufacturer | | 3.31.4 | 2017-10-21 | updated `README.md` | diff --git a/lib/battery.js b/lib/battery.js index 86ee9dc..b99ebec 100644 --- a/lib/battery.js +++ b/lib/battery.js @@ -22,11 +22,10 @@ let _platform = os.type(); const _linux = (_platform === 'Linux'); const _darwin = (_platform === 'Darwin'); const _windows = (_platform === 'Windows_NT'); -const NOT_SUPPORTED = 'not supported'; module.exports = function (callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = { hasbattery: false, @@ -40,27 +39,27 @@ module.exports = function (callback) { if (_linux) { let battery_path = ''; if (fs.existsSync('/sys/class/power_supply/BAT1/status')) { - battery_path = '/sys/class/power_supply/BAT1/' + battery_path = '/sys/class/power_supply/BAT1/'; } else if (fs.existsSync('/sys/class/power_supply/BAT0/status')) { - battery_path = '/sys/class/power_supply/BAT0/' + battery_path = '/sys/class/power_supply/BAT0/'; } if (battery_path) { - exec("cat " + battery_path + "status", function (error, stdout) { + exec('cat ' + battery_path + 'status', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); - if (lines.length > 0 && lines[0]) result.ischarging = (lines[0].trim().toLowerCase() === 'charging') + if (lines.length > 0 && lines[0]) result.ischarging = (lines[0].trim().toLowerCase() === 'charging'); } - exec("cat " + battery_path + "cyclec_ount", function (error, stdout) { + exec('cat ' + battery_path + 'cyclec_ount', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); if (lines.length > 0 && lines[0]) result.cyclecount = parseFloat(lines[0].trim()); } - exec("cat " + battery_path + "charge_full", function (error, stdout) { + exec('cat ' + battery_path + 'charge_full', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); if (lines.length > 0 && lines[0]) result.maxcapacity = parseFloat(lines[0].trim()); } - exec("cat " + battery_path + "charge_now", function (error, stdout) { + exec('cat ' + battery_path + 'charge_now', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); if (lines.length > 0 && lines[0]) result.currentcapacity = parseFloat(lines[0].trim()); @@ -69,21 +68,21 @@ module.exports = function (callback) { result.hasbattery = true; result.percent = 100.0 * result.currentcapacity / result.maxcapacity; } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); - }) - }) - }) - }) + }); + }); + }); + }); } else { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } } if (_darwin) { exec("ioreg -n AppleSmartBattery -r | grep '\"CycleCount\"';ioreg -n AppleSmartBattery -r | grep '\"IsCharging\"';ioreg -n AppleSmartBattery -r | grep '\"MaxCapacity\"';ioreg -n AppleSmartBattery -r | grep '\"CurrentCapacity\"'", function (error, stdout) { if (!error) { - let lines = stdout.toString().replace(/ +/g, "").replace(/"+/g, "").split('\n'); + let lines = stdout.toString().replace(/ +/g, '').replace(/"+/g, '').split('\n'); lines.forEach(function (line) { if (line.indexOf('=') !== -1) { if (line.toLowerCase().indexOf('cyclecount') !== -1) result.cyclecount = parseFloat(line.split('=')[1].trim()); @@ -97,12 +96,12 @@ module.exports = function (callback) { result.hasbattery = true; result.percent = 100.0 * result.currentcapacity / result.maxcapacity; } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } if (_windows) { - exec("WMIC Path Win32_Battery Get BatteryStatus, DesignCapacity, EstimatedChargeRemaining /value", function (error, stdout) { + exec('WMIC Path Win32_Battery Get BatteryStatus, DesignCapacity, EstimatedChargeRemaining /value', function (error, stdout) { if (stdout) { let lines = stdout.split('\r\n'); let status = util.getValue(lines, 'BatteryStatus', '=').trim(); @@ -115,7 +114,7 @@ module.exports = function (callback) { result.ischarging = (status >= 6 && status <= 9) || (!(status === 3) && !(status === 1) && result.percent < 100); } } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } diff --git a/lib/cpu.js b/lib/cpu.js index 960493b..e9a5755 100644 --- a/lib/cpu.js +++ b/lib/cpu.js @@ -22,7 +22,6 @@ let _platform = os.type(); const _linux = (_platform === 'Linux'); const _darwin = (_platform === 'Darwin'); const _windows = (_platform === 'Windows_NT'); -const NOT_SUPPORTED = 'not supported'; let _cpu_speed = '0.00'; let _current_cpu = { @@ -50,11 +49,73 @@ let _current_cpu = { let _cpus = []; let _corecount = 0; +const AMDBaseFrequencies = { + 'FX|4100': '3.6', + 'FX|4120': '3.9', + 'FX|4130': '3.8', + 'FX|4150': '3.8', + 'FX|4170': '4.2', + 'FX|6100': '3.3', + 'FX|6120': '3.6', + 'FX|6130': '3.6', + 'FX|6200': '3.8', + 'FX|8100': '2.8', + 'FX|8120': '3.1', + 'FX|8140': '3.2', + 'FX|8150': '3.6', + 'FX|8170': '3.9', + 'FX|4300': '3.8', + 'FX|4320': '4.0', + 'FX|4350': '4.2', + 'FX|6300': '3.5', + 'FX|6350': '3.9', + 'FX|8300': '3.3', + 'FX|8310': '3.4', + 'FX|8320': '3.5', + 'FX|8350': '4.0', + 'FX|8370': '4.0', + 'FX|9370': '4.4', + 'FX|9590': '4.7', + 'FX|8320E': '3.2', + 'FX|8370E': '3.3', + '1950X': '3.4', + '1920X': '3.5', + '1920': '3.2', + '1900X': '3.8', + '1800X': '3.6', + '1700X': '3.4', + 'Pro 1700X': '3.5', + '1700': '3.0', + 'Pro 1700': '3.0', + '1600X': '3.6', + '1600': '3.2', + 'Pro 1600': '3.2', + '1500X': '3.5', + 'Pro 1500': '3.5', + '1400': '3.2', + '1300X': '3.5', + 'Pro 1300': '3.5', + '1200': '3.1', + 'Pro 1200': '3.1', + '7601': '2.2', + '7551': '2.0', + '7501': '2.0', + '74501': '2.3', + '7401': '2.0', + '7351': '2.4', + '7301': '2.2', + '7281': '2.1', + '7251': '2.1', + '7551P': '2.0', + '7401P': '2.0', + '7351P': '2.4' +}; + function cpuBrandManufacturer(res) { - res.brand = res.brand.replace(/\(R\)+/g, "®"); - res.brand = res.brand.replace(/\(TM\)+/g, "™"); - res.brand = res.brand.replace(/\(C\)+/g, "©"); - res.brand = res.brand.replace(/CPU+/g, "").trim(); + res.brand = res.brand.replace(/\(R\)+/g, '®'); + res.brand = res.brand.replace(/\(TM\)+/g, '™'); + res.brand = res.brand.replace(/\(C\)+/g, '©'); + res.brand = res.brand.replace(/CPU+/g, '').trim(); res.manufacturer = res.brand.split(' ')[0]; let parts = res.brand.split(' '); @@ -63,6 +124,26 @@ function cpuBrandManufacturer(res) { return res; } +function getAMDSpeed(brand) { + let result = '0.00'; + for (let key in AMDBaseFrequencies) { + if (AMDBaseFrequencies.hasOwnProperty(key)) { + let parts = key.split('|'); + //console.log(item); + let found = 0; + parts.forEach(item => { + if (brand.indexOf(item) > -1) { + found++; + } + }); + if (found === parts.length) { + result = AMDBaseFrequencies[key]; + } + } + } + return result; +} + // -------------------------- // CPU - brand, speed @@ -70,7 +151,7 @@ function getCpu() { return new Promise((resolve) => { process.nextTick(() => { - const UNKNOWN = 'unknown' + const UNKNOWN = 'unknown'; let result = { manufacturer: UNKNOWN, brand: UNKNOWN, @@ -86,13 +167,13 @@ function getCpu() { cache: {} }; if (_darwin) { - exec("sysctl machdep.cpu hw.cpufrequency_max hw.cpufrequency_min", function (error, stdout) { + exec('sysctl machdep.cpu hw.cpufrequency_max hw.cpufrequency_min', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); const modelline = util.getValue(lines, 'machdep.cpu.brand_string'); result.brand = modelline.split('@')[0].trim(); result.speed = modelline.split('@')[1].trim(); - result.speed = parseFloat(result.speed.replace(/GHz+/g, "")).toFixed(2); + result.speed = parseFloat(result.speed.replace(/GHz+/g, '')).toFixed(2); _cpu_speed = result.speed; result = cpuBrandManufacturer(result); result.speedmin = (util.getValue(lines, 'hw.cpufrequency_min') / 1000000000.0 ).toFixed(2); @@ -106,25 +187,28 @@ function getCpu() { cpuCache().then(res => { result.cache = res; resolve(result); - }) + }); }); } if (_linux) { - exec("export LC_ALL=C; lscpu; unset LC_ALL", function (error, stdout) { + exec('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); const modelline = util.getValue(lines, 'model name'); result.brand = modelline.split('@')[0].trim(); result.speed = modelline.split('@')[1] ? parseFloat(modelline.split('@')[1].trim()).toFixed(2) : '0.00'; + if (result.speed === '0.00' && result.brand.indexOf('AMD') > -1) { + result.speed = getAMDSpeed(result.brand); + } if (result.speed === '0.00') { let current = getCpuCurrentSpeedSync(); if (current !== '0.00') result.speed = current; } _cpu_speed = result.speed; result.speedmin = Math.round(parseFloat(util.getValue(lines, 'cpu min mhz').replace(/,/g, '.')) / 10.0) / 100; - result.speedmin = result.speedmin ? parseFloat(result.speedmin).toFixed(2) : '' + result.speedmin = result.speedmin ? parseFloat(result.speedmin).toFixed(2) : ''; result.speedmax = Math.round(parseFloat(util.getValue(lines, 'cpu max mhz').replace(/,/g, '.')) / 10.0) / 100; - result.speedmax = result.speedmax ? parseFloat(result.speedmax).toFixed(2) : '' + result.speedmax = result.speedmax ? parseFloat(result.speedmax).toFixed(2) : ''; result = cpuBrandManufacturer(result); result.vendor = util.getValue(lines, 'vendor id'); @@ -136,28 +220,26 @@ function getCpu() { result.stepping = util.getValue(lines, 'stepping'); result.revision = util.getValue(lines, 'cpu revision'); result.cache.l1d = util.getValue(lines, 'l1d cache'); - if (result.cache.l1d) { result.cache.l1d = parseInt(result.cache.l1d) * (result.cache.l1d.indexOf('K') !== -1 ? 1024 : 1)} + if (result.cache.l1d) { result.cache.l1d = parseInt(result.cache.l1d) * (result.cache.l1d.indexOf('K') !== -1 ? 1024 : 1); } result.cache.l1i = util.getValue(lines, 'l1i cache'); - if (result.cache.l1i) { result.cache.l1i = parseInt(result.cache.l1i) * (result.cache.l1i.indexOf('K') !== -1 ? 1024 : 1)} + if (result.cache.l1i) { result.cache.l1i = parseInt(result.cache.l1i) * (result.cache.l1i.indexOf('K') !== -1 ? 1024 : 1); } result.cache.l2 = util.getValue(lines, 'l2 cache'); - if (result.cache.l2) { result.cache.l2 = parseInt(result.cache.l2) * (result.cache.l2.indexOf('K') !== -1 ? 1024 : 1)} + if (result.cache.l2) { result.cache.l2 = parseInt(result.cache.l2) * (result.cache.l2.indexOf('K') !== -1 ? 1024 : 1); } result.cache.l3 = util.getValue(lines, 'l3 cache'); - if (result.cache.l3) { result.cache.l3 = parseInt(result.cache.l3) * (result.cache.l3.indexOf('K') !== -1 ? 1024 : 1)} - } else { - + if (result.cache.l3) { result.cache.l3 = parseInt(result.cache.l3) * (result.cache.l3.indexOf('K') !== -1 ? 1024 : 1); } } resolve(result); - }) + }); } if (_windows) { - exec("wmic cpu get name, description, revision, l2cachesize, l3cachesize, manufacturer, currentclockspeed, maxclockspeed /value", function (error, stdout) { + exec('wmic cpu get name, description, revision, l2cachesize, l3cachesize, manufacturer, currentclockspeed, maxclockspeed /value', function (error, stdout) { if (!error) { let lines = stdout.split('\r\n'); let name = util.getValue(lines, 'name', '=') || ''; if (name.indexOf('@') >= 0) { result.brand = name.split('@')[0].trim(); result.speed = name.split('@')[1].trim(); - result.speed = parseFloat(result.speed.replace(/GHz+/g, "").trim()).toFixed(2); + result.speed = parseFloat(result.speed.replace(/GHz+/g, '').trim()).toFixed(2); _cpu_speed = result.speed; } else { result.brand = name.split('@')[0].trim(); @@ -169,29 +251,29 @@ function getCpu() { result.cache.l1i = 0; result.cache.l2 = util.getValue(lines, 'l2cachesize', '='); result.cache.l3 = util.getValue(lines, 'l3cachesize', '='); - if (result.cache.l2) { result.cache.l2 = parseInt(result.cache.l2) * 1024} - if (result.cache.l3) { result.cache.l3 = parseInt(result.cache.l3) * 1024} + if (result.cache.l2) { result.cache.l2 = parseInt(result.cache.l2, 10) * 1024; } + if (result.cache.l3) { result.cache.l3 = parseInt(result.cache.l3, 10) * 1024; } result.vendor = util.getValue(lines, 'manufacturer', '='); result.speedmax = Math.round(parseFloat(util.getValue(lines, 'maxclockspeed', '=').replace(/,/g, '.')) / 10.0) / 100; result.speedmax = result.speedmax ? parseFloat(result.speedmax).toFixed(2) : ''; if (!result.speed) { - result.speed = result.speedmax + result.speed = result.speedmax; } let description = util.getValue(lines, 'description', '=').split(' '); for (let i = 0; i < description.length; i++) { if (description[i].toLowerCase().startsWith('family') && (i+1) < description.length && description[i+1]) { - result.family = description[i+1] + result.family = description[i+1]; } if (description[i].toLowerCase().startsWith('model') && (i+1) < description.length && description[i+1]) { - result.model = description[i+1] + result.model = description[i+1]; } if (description[i].toLowerCase().startsWith('stepping') && (i+1) < description.length && description[i+1]) { - result.stepping = description[i+1] + result.stepping = description[i+1]; } } } - exec("wmic path Win32_CacheMemory get CacheType,InstalledSize,Purpose", function (error, stdout) { + exec('wmic path Win32_CacheMemory get CacheType,InstalledSize,Purpose', function (error, stdout) { if (!error) { let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0); lines.forEach(function (line) { @@ -199,18 +281,18 @@ function getCpu() { line = line.trim().split(/\s\s+/); // L1 Instructions if (line[2] === 'L1 Cache' && line[0] === '3') { - result.cache.l1i = parseInt(line[1], 10) + result.cache.l1i = parseInt(line[1], 10); } // L1 Data if (line[2] === 'L1 Cache' && line[0] === '4') { - result.cache.l1d = parseInt(line[1], 10) + result.cache.l1d = parseInt(line[1], 10); } } }); } resolve(result); - }) - }) + }); + }); } }); }); @@ -221,12 +303,12 @@ function getCpu() { function cpu(callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { getCpu().then(result => { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); - }) + }); }); }); } @@ -256,13 +338,13 @@ function getCpuCurrentSpeedSync() { min: parseFloat(((minFreq + 1) / 1000).toFixed(2)), max: parseFloat(((maxFreq + 1) / 1000).toFixed(2)), avg: parseFloat(((avgFreq + 1) / 1000).toFixed(2)) - } + }; } else { return { min: 0, max: 0, avg: 0 - } + }; } } @@ -273,7 +355,7 @@ function cpuCurrentspeed(callback) { let result = getCpuCurrentSpeedSync(); if (result === 0 && _cpu_speed !== '0.00') result = parseFloat(_cpu_speed); - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); }); @@ -287,7 +369,7 @@ exports.cpuCurrentspeed = cpuCurrentspeed; function cpuTemperature(callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = { main: -1.0, @@ -295,7 +377,7 @@ function cpuTemperature(callback) { max: -1.0 }; if (_linux) { - exec("sensors", function (error, stdout) { + exec('sensors', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { @@ -312,32 +394,32 @@ function cpuTemperature(callback) { let maxtmp = Math.max.apply(Math, result.cores); result.max = (maxtmp > result.main) ? maxtmp : result.main; } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } else { - fs.stat('/sys/class/thermal/thermal_zone0/temp', function(err, stat) { + fs.stat('/sys/class/thermal/thermal_zone0/temp', function(err) { if(err === null) { - exec("cat /sys/class/thermal/thermal_zone0/temp", function (error, stdout) { + exec('cat /sys/class/thermal/thermal_zone0/temp', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); if (lines.length > 0) { result.main = parseFloat(lines[0]) / 1000.0; - result.max = result.main + result.max = result.main; } } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } else { - exec("/opt/vc/bin/vcgencmd measure_temp", function (error, stdout) { + exec('/opt/vc/bin/vcgencmd measure_temp', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); if (lines.length > 0 && lines[0].indexOf('=')) { - result.main = parseFloat(lines[0].split("=")[1]); - result.max = result.main + result.main = parseFloat(lines[0].split('=')[1]); + result.max = result.main; } } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } @@ -351,17 +433,17 @@ function cpuTemperature(callback) { try { osxTemp = require('osx-temperature-sensor'); } catch (er) { - osxTemp = null + osxTemp = null; } if (osxTemp) { result = osxTemp.cpuTemperature(); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } if (_windows) { - exec("wmic /namespace:\\\\root\\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature", function (error, stdout) { + exec('wmic /namespace:\\\\root\\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature', function (error, stdout) { if (!error) { let sum = 0; let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0); @@ -375,7 +457,7 @@ function cpuTemperature(callback) { result.main = sum / result.cores.length; } } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } @@ -390,36 +472,36 @@ exports.cpuTemperature = cpuTemperature; function cpuFlags(callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = ''; if (_windows) { - exec(`reg query "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0" /v FeatureSet`, function (error, stdout) { + exec('reg query "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0" /v FeatureSet', function (error, stdout) { if (!error) { - let flag_hex = stdout.split("0x").pop().trim(); + let flag_hex = stdout.split('0x').pop().trim(); let flag_bin_unpadded = parseInt(flag_hex, 16).toString(2); - let flag_bin = "0".repeat(32 - flag_bin_unpadded.length) + flag_bin_unpadded; + let flag_bin = '0'.repeat(32 - flag_bin_unpadded.length) + flag_bin_unpadded; // empty flags are the reserved fields in the CPUID feature bit list // as found on wikipedia: // https://en.wikipedia.org/wiki/CPUID let all_flags = [ - "fpu", "vme", "de", "pse", "tsc", "msr", "pae", "mce", "cx8", "apic", - "", "sep", "mtrr", "pge", "mca", "cmov", "pat", "pse-36", "psn", "clfsh", - "", "ds", "acpi", "mmx", "fxsr", "sse", "sse2", "ss", "htt", "tm", "ia64", "pbe" - ] + 'fpu', 'vme', 'de', 'pse', 'tsc', 'msr', 'pae', 'mce', 'cx8', 'apic', + '', 'sep', 'mtrr', 'pge', 'mca', 'cmov', 'pat', 'pse-36', 'psn', 'clfsh', + '', 'ds', 'acpi', 'mmx', 'fxsr', 'sse', 'sse2', 'ss', 'htt', 'tm', 'ia64', 'pbe' + ]; for (let f = 0; f < all_flags.length; f++) { - if (flag_bin[f] === "1" && all_flags[f] !== "") { - result += " " + all_flags[f]; + if (flag_bin[f] === '1' && all_flags[f] !== '') { + result += ' ' + all_flags[f]; } } result = result.trim(); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } if (_linux) { - exec("lscpu", function (error, stdout) { + exec('lscpu', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { @@ -428,19 +510,19 @@ function cpuFlags(callback) { } }); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } if (_darwin) { - exec("sysctl machdep.cpu.features", function (error, stdout) { + exec('sysctl machdep.cpu.features', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); if (lines.length > 0 && lines[0].indexOf('machdep.cpu.features:') !== -1) { result = lines[0].split(':')[1].trim().toLowerCase(); } } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } @@ -455,12 +537,12 @@ exports.cpuFlags = cpuFlags; function cpuCache(callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = {}; if (_linux) { - exec("lscpu", function (error, stdout) { + exec('lscpu', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { @@ -479,12 +561,12 @@ function cpuCache(callback) { } }); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } if (_darwin) { - exec("sysctl hw.l1icachesize hw.l1dcachesize hw.l2cachesize hw.l3cachesize", function (error, stdout) { + exec('sysctl hw.l1icachesize hw.l1dcachesize hw.l2cachesize hw.l3cachesize', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { @@ -503,22 +585,22 @@ function cpuCache(callback) { } }); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } if (_windows) { - exec("wmic cpu get l2cachesize, l3cachesize /value", function (error, stdout) { + exec('wmic cpu get l2cachesize, l3cachesize /value', function (error, stdout) { if (!error) { let lines = stdout.split('\r\n'); result.l1d = 0; result.l1i = 0; result.l2 = util.getValue(lines, 'l2cachesize', '='); result.l3 = util.getValue(lines, 'l3cachesize', '='); - if (result.l2) { result.l2 = parseInt(result.l2) * 1024} - if (result.l3) { result.l3 = parseInt(result.l3) * 1024} + if (result.l2) { result.l2 = parseInt(result.l2) * 1024; } + if (result.l3) { result.l3 = parseInt(result.l3) * 1024; } } - exec("wmic path Win32_CacheMemory get CacheType,InstalledSize,Purpose", function (error, stdout) { + exec('wmic path Win32_CacheMemory get CacheType,InstalledSize,Purpose', function (error, stdout) { if (!error) { let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0); lines.forEach(function (line) { @@ -526,19 +608,19 @@ function cpuCache(callback) { line = line.trim().split(/\s\s+/); // L1 Instructions if (line[2] === 'L1 Cache' && line[0] === '3') { - result.l1i = parseInt(line[1], 10) + result.l1i = parseInt(line[1], 10); } // L1 Data if (line[2] === 'L1 Cache' && line[0] === '4') { - result.l1d = parseInt(line[1], 10) + result.l1d = parseInt(line[1], 10); } } }); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); - }) - }) + }); + }); } }); }); @@ -553,7 +635,7 @@ function getLoad() { return new Promise((resolve) => { process.nextTick(() => { - let loads = os.loadavg().map(function (x) { return x / util.cores() }); + let loads = os.loadavg().map(function (x) { return x / util.cores(); }); let avgload = parseFloat((Math.max.apply(Math, loads)).toFixed(2)); let result = {}; @@ -692,9 +774,9 @@ function currentLoad(callback) { return new Promise((resolve) => { process.nextTick(() => { getLoad().then(result => { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); - }) + }); }); }); } @@ -738,9 +820,9 @@ function fullLoad(callback) { return new Promise((resolve) => { process.nextTick(() => { getFullLoad().then(result => { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); - }) + }); }); }); } diff --git a/lib/docker.js b/lib/docker.js index 3dcd4c5..9ac3a7f 100644 --- a/lib/docker.js +++ b/lib/docker.js @@ -12,15 +12,9 @@ // 13. Docker // ---------------------------------------------------------------------------------- -const os = require('os'); const util = require('./util'); const DockerSocket = require('./dockerSocket'); -let _platform = os.type(); - -const _windows = (_platform === 'Windows_NT'); -const NOT_SUPPORTED = 'not supported'; - let _docker_container_stats = {}; let _docker_socket; @@ -36,7 +30,7 @@ function dockerContainers(all, callback) { * @namespace * @property {string} Id */ - return (obj.Id && (obj.Id === id)) + return (obj.Id && (obj.Id === id)); }); return (filtered.length > 0); } @@ -49,7 +43,7 @@ function dockerContainers(all, callback) { all = all || false; let result = []; - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { if (!_docker_socket) { _docker_socket = new DockerSocket(); @@ -95,7 +89,7 @@ function dockerContainers(all, callback) { mounts: element.Mounts, // hostconfig: element.HostConfig, // network: element.NetworkSettings - }) + }); }); } } catch (err) { @@ -108,7 +102,7 @@ function dockerContainers(all, callback) { if (!inContainers(docker_containers, key)) delete _docker_container_stats[key]; } } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); }); @@ -143,7 +137,7 @@ function docker_calcCPUPercent(cpu_stats, id) { _docker_container_stats[id].prev_CPU = cpu_stats.cpu_usage.total_usage; _docker_container_stats[id].prev_system = cpu_stats.system_cpu_usage; - return cpuPercent + return cpuPercent; } function docker_calcNetworkIO(networks) { @@ -165,7 +159,7 @@ function docker_calcNetworkIO(networks) { return { rx: rx, tx: tx - } + }; } function docker_calcBlockIO(blkio_stats) { @@ -192,7 +186,7 @@ function docker_calcBlockIO(blkio_stats) { if (element.op && element.op.toLowerCase() === 'write' && element.value) { result.w += element.value; } - }) + }); } return result; } @@ -218,7 +212,7 @@ function dockerContainerStats(containerID, callback) { w: 0 } }; - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { if (containerID) { @@ -232,7 +226,7 @@ function dockerContainerStats(containerID, callback) { // if (!error) { // let jsonString = stdout.toString(); try { -// let stats = JSON.parse(jsonString); + // let stats = JSON.parse(jsonString); let stats = data; /** * @namespace @@ -262,11 +256,11 @@ function dockerContainerStats(containerID, callback) { } catch (err) { } // } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } else { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } }); @@ -281,7 +275,7 @@ exports.dockerContainerStats = dockerContainerStats; function dockerContainerProcesses(containerID, callback) { containerID = containerID || ''; let result = []; - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { if (containerID) { @@ -295,7 +289,7 @@ function dockerContainerProcesses(containerID, callback) { * @property {Array} Titles * @property {Array} Processes **/ - try { + try { if (data && data.Titles && data.Processes) { let titles = data.Titles.map(function(value) { return value.toUpperCase(); @@ -331,16 +325,16 @@ function dockerContainerProcesses(containerID, callback) { rss: (pos_rss >= 0 ? process[pos_rss] : ''), vsz: (pos_vsz >= 0 ? process[pos_vsz] : ''), command: (pos_command >= 0 ? process[pos_command] : '') - }) - }) + }); + }); } } catch (err) { } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } else { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } }); @@ -350,7 +344,7 @@ function dockerContainerProcesses(containerID, callback) { exports.dockerContainerProcesses = dockerContainerProcesses; function dockerAll(callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { dockerContainers(true).then(result => { if (result && Object.prototype.toString.call(result) === '[object Array]' && result.length > 0) { @@ -375,18 +369,18 @@ function dockerAll(callback) { l -= 1; if (l === 0) { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } }); // all done?? - }) - }) + }); + }); } else { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } - }) + }); }); }); } diff --git a/lib/dockerSocket.js b/lib/dockerSocket.js index fde4ceb..c0d3c63 100644 --- a/lib/dockerSocket.js +++ b/lib/dockerSocket.js @@ -24,21 +24,21 @@ class DockerSocket { let socket = net.createConnection({path: socketPath}); let alldata = ''; - socket.on("connect", () => { - socket.write('GET http:/containers/json' + (all ? "?all=1" : "") + ' HTTP/1.0\r\n\r\n'); + socket.on('connect', () => { + socket.write('GET http:/containers/json' + (all ? '?all=1' : '') + ' HTTP/1.0\r\n\r\n'); }); - socket.on("data", data => { + socket.on('data', data => { alldata = alldata + data.toString(); }); - socket.on("error", () => { + socket.on('error', () => { socket = false; callback({}); }); socket.on('end', () => { - let startbody = alldata.indexOf("\r\n\r\n"); + let startbody = alldata.indexOf('\r\n\r\n'); alldata = alldata.substring(startbody, 100000).replace(/[\n\r]/g, ''); socket = false; callback(JSON.parse(alldata)); @@ -55,21 +55,21 @@ class DockerSocket { let socket = net.createConnection({path: socketPath}); let alldata = ''; - socket.on("connect", () => { + socket.on('connect', () => { socket.write('GET http:/containers/' + id + '/stats?stream=0 HTTP/1.0\r\n\r\n'); }); - socket.on("data", data => { + socket.on('data', data => { alldata = alldata + data.toString(); }); - socket.on("error", () => { + socket.on('error', () => { socket = false; callback({}); }); socket.on('end', () => { - let startbody = alldata.indexOf("\r\n\r\n"); + let startbody = alldata.indexOf('\r\n\r\n'); alldata = alldata.substring(startbody, 100000).replace(/[\n\r]/g, ''); socket = false; callback(JSON.parse(alldata)); @@ -89,21 +89,21 @@ class DockerSocket { let socket = net.createConnection({path: socketPath}); let alldata = ''; - socket.on("connect", () => { + socket.on('connect', () => { socket.write('GET http:/containers/' + id + '/top?ps_args=-opid,ppid,pgid,vsz,time,etime,nice,ruser,user,rgroup,group,stat,rss,args HTTP/1.0\r\n\r\n'); }); - socket.on("data", data => { + socket.on('data', data => { alldata = alldata + data.toString(); }); - socket.on("error", () => { + socket.on('error', () => { socket = false; callback({}); }); socket.on('end', () => { - let startbody = alldata.indexOf("\r\n\r\n"); + let startbody = alldata.indexOf('\r\n\r\n'); alldata = alldata.substring(startbody, 100000).replace(/[\n\r]/g, ''); socket = false; callback(JSON.parse(alldata)); diff --git a/lib/filesystem.js b/lib/filesystem.js index fc2d25c..f189159 100644 --- a/lib/filesystem.js +++ b/lib/filesystem.js @@ -15,7 +15,6 @@ const os = require('os'); const exec = require('child_process').exec; const execSync = require('child_process').execSync; -const fs = require('fs'); const util = require('./util'); let _platform = os.type(); @@ -33,18 +32,18 @@ let _disk_io = {}; function fsSize(callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let data = []; if (_linux || _darwin) { - let cmd = (_darwin ? "df -lkP | grep ^/" : "df -lkPT | grep ^/"); + let cmd = (_darwin ? 'df -lkP | grep ^/' : 'df -lkPT | grep ^/'); exec(cmd, function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); //lines.splice(0, 1); lines.forEach(function (line) { if (line !== '') { - line = line.replace(/ +/g, " ").split(' '); + line = line.replace(/ +/g, ' ').split(' '); data.push({ 'fs': line[0], 'type': (_linux ? line[1] : 'HFS'), @@ -52,12 +51,12 @@ function fsSize(callback) { 'used': parseInt((_linux ? line[3] : line[2])) * 1024, 'use': parseFloat((100.0 * (_linux ? line[3] : line[2]) / (_linux ? line[2] : line[1])).toFixed(2)), 'mount': line[line.length - 1] - }) + }); } }); } if (callback) { - callback(data) + callback(data); } resolve(data); }); @@ -75,11 +74,11 @@ function fsSize(callback) { 'used': parseInt(line[3]) - parseInt(line[2]), 'use': parseFloat((100.0 * (parseInt(line[3]) - parseInt(line[2]))) / parseInt(line[3])), 'mount': line[0] - }) + }); } }); if (callback) { - callback(data) + callback(data); } resolve(data); }); @@ -94,7 +93,7 @@ exports.fsSize = fsSize; // disks function parseBytes(s) { - return parseInt(s.substr(s.indexOf(' (') + 2, s.indexOf(' Bytes)') - 10)) + return parseInt(s.substr(s.indexOf(' (') + 2, s.indexOf(' Bytes)') - 10)); } function parseDevices(lines) { @@ -167,7 +166,7 @@ function parseBlk(lines) { 'serial': disk.serial, 'removable': disk.rm === '1', 'protocol': disk.tran - }) + }); }); data = util.unique(data); @@ -196,28 +195,28 @@ function blkStdoutToObject(stdout) { function blockDevices(callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let data = []; if (_linux) { // see https://wiki.ubuntuusers.de/lsblk/ // exec("lsblk -bo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,TRAN,SERIAL,LABEL,MODEL,OWNER,GROUP,MODE,ALIGNMENT,MIN-IO,OPT-IO,PHY-SEC,LOG-SEC,SCHED,RQ-SIZE,RA,WSAME", function (error, stdout) { - exec("lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,TRAN,SERIAL,LABEL,MODEL,OWNER", function (error, stdout) { + exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,TRAN,SERIAL,LABEL,MODEL,OWNER', function (error, stdout) { if (!error) { let lines = blkStdoutToObject(stdout).split('\n'); data = parseBlk(lines); if (callback) { - callback(data) + callback(data); } resolve(data); } else { - exec("lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER", function (error, stdout) { + exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER', function (error, stdout) { if (!error) { let lines = blkStdoutToObject(stdout).split('\n'); data = parseBlk(lines); } if (callback) { - callback(data) + callback(data); } resolve(data); }); @@ -225,14 +224,14 @@ function blockDevices(callback) { }); } if (_darwin) { - exec("diskutil info -all", function (error, stdout) { + exec('diskutil info -all', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); // parse lines into temp array of devices data = parseDevices(lines); } if (callback) { - callback(data) + callback(data); } resolve(data); }); @@ -263,7 +262,7 @@ function blockDevices(callback) { }); } if (callback) { - callback(data) + callback(data); } resolve(data); }); @@ -327,7 +326,7 @@ function fsStats(callback) { if (_windows) { let error = new Error(NOT_SUPPORTED); if (callback) { - callback(NOT_SUPPORTED) + callback(NOT_SUPPORTED); } reject(error); } @@ -346,15 +345,15 @@ function fsStats(callback) { let wx = 0; if ((_fs_speed && !_fs_speed.ms) || (_fs_speed && _fs_speed.ms && Date.now() - _fs_speed.ms >= 500)) { if (_linux) { -// exec("df -k | grep /dev/", function(error, stdout) { - exec("lsblk | grep /", function (error, stdout) { + // exec("df -k | grep /dev/", function(error, stdout) { + exec('lsblk | grep /', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); let fs_filter = []; lines.forEach(function (line) { if (line !== '') { - line = line.replace(/[├─│└]+/g, "").trim().split(' '); - if (fs_filter.indexOf(line[0]) === -1) fs_filter.push(line[0]) + line = line.replace(/[├─│└]+/g, '').trim().split(' '); + if (fs_filter.indexOf(line[0]) === -1) fs_filter.push(line[0]); } }); @@ -365,7 +364,7 @@ function fsStats(callback) { lines.forEach(function (line) { line = line.trim(); if (line !== '') { - line = line.replace(/ +/g, " ").split(' '); + line = line.replace(/ +/g, ' ').split(' '); rx += parseInt(line[5]) * 512; wx += parseInt(line[9]) * 512; @@ -374,17 +373,17 @@ function fsStats(callback) { result = calcFsSpeed(rx, wx); } if (callback) { - callback(result) + callback(result); } resolve(result); - }) + }); } else { if (callback) { - callback(result) + callback(result); } resolve(result); } - }) + }); } if (_darwin) { exec("ioreg -c IOBlockStorageDriver -k Statistics -r -w0 | sed -n '/IOBlockStorageDriver/,/Statistics/p' | grep 'Statistics' | tr -cd '01234567890,\n' | awk -F',' '{print $3, $10}'", function (error, stdout) { @@ -402,10 +401,10 @@ function fsStats(callback) { result = calcFsSpeed(rx, wx); } if (callback) { - callback(result) + callback(result); } resolve(result); - }) + }); } } else { result.ms = _fs_speed.last_ms; @@ -416,7 +415,7 @@ function fsStats(callback) { result.wx_sec = _fs_speed.wx_sec; result.tx_sec = _fs_speed.tx_sec; if (callback) { - callback(result) + callback(result); } resolve(result); } @@ -473,7 +472,7 @@ function disksIO(callback) { if (_windows) { let error = new Error(NOT_SUPPORTED); if (callback) { - callback(NOT_SUPPORTED) + callback(NOT_SUPPORTED); } reject(error); } @@ -512,12 +511,12 @@ function disksIO(callback) { result = calcDiskIO(rIO, wIO); if (callback) { - callback(result) + callback(result); } resolve(result); } else { if (callback) { - callback(result) + callback(result); } resolve(result); } @@ -539,7 +538,7 @@ function disksIO(callback) { result = calcDiskIO(rIO, wIO); } if (callback) { - callback(result) + callback(result); } resolve(result); }) @@ -553,7 +552,7 @@ function disksIO(callback) { result.wIO_sec = _disk_io.wIO_sec; result.tIO_sec = _disk_io.tIO_sec; if (callback) { - callback(result) + callback(result); } resolve(result); } @@ -565,13 +564,13 @@ exports.disksIO = disksIO; function diskLayout(callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = []; if (_linux) { - exec("export LC_ALL=C; lshw -class disk; unset LC_ALL", function (error, stdout) { + exec('export LC_ALL=C; lshw -class disk; unset LC_ALL', function (error, stdout) { if (!error) { let devices = stdout.toString().split('*-'); devices.shift(); @@ -601,19 +600,19 @@ function diskLayout(callback) { firmwareRevision: util.getValue(lines, 'version:', ':', true).trim(), serialNum: util.getValue(lines, 'serial:', ':', true).trim(), interfaceType: '', - }) + }); } }); } if (callback) { - callback(result) + callback(result); } resolve(result); }); } if (_darwin) { - exec("system_profiler SPSerialATADataType SPNVMeDataType", function (error, stdout) { + exec('system_profiler SPSerialATADataType SPNVMeDataType', function (error, stdout) { if (!error) { let parts = stdout.toString().split('NVMExpress:'); @@ -625,7 +624,7 @@ function diskLayout(callback) { const mediumType = util.getValue(lines, 'Medium Type', ':', true).trim(); const sizeStr = util.getValue(lines, 'capacity', ':', true).trim(); if (sizeStr) { - let size = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, "")); + let size = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '')); if (!size) { size = parseInt(sizeStr); } @@ -645,7 +644,7 @@ function diskLayout(callback) { firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(), serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(), interfaceType: util.getValue(lines, 'InterfaceType', ':', true).trim() - }) + }); } } }); @@ -658,7 +657,7 @@ function diskLayout(callback) { const linkWidth = util.getValue(lines, 'link width', ':', true).trim(); const sizeStr = util.getValue(lines, '!capacity', ':', true).trim(); if (sizeStr) { - let size = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, "")); + let size = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '')); if (!size) { size = parseInt(sizeStr); } @@ -678,21 +677,21 @@ function diskLayout(callback) { firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(), serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(), interfaceType: ('PCIe ' + linkWidth).trim(), - }) + }); } } }); } } if (callback) { - callback(result) + callback(result); } resolve(result); }); } if (_windows) { - exec("wmic diskdrive get /value", function (error, stdout) { + exec('wmic diskdrive get /value', function (error, stdout) { if (!error) { let devices = stdout.toString().split('\r\n\r\n\r\n'); devices.forEach(function (device) { @@ -714,12 +713,12 @@ function diskLayout(callback) { firmwareRevision: util.getValue(lines, 'FirmwareRevision', '=').trim(), serialNum: util.getValue(lines, 'SerialNumber', '=').trim(), interfaceType: util.getValue(lines, 'InterfaceType', '=').trim() - }) + }); } }); } if (callback) { - callback(result) + callback(result); } resolve(result); }); diff --git a/lib/graphics.js b/lib/graphics.js index a19fdf7..ed01390 100644 --- a/lib/graphics.js +++ b/lib/graphics.js @@ -30,7 +30,7 @@ function toInt(value) { if (isNaN(result)) { result = 0; } - return result + return result; } function graphics(callback) { @@ -63,14 +63,14 @@ function graphics(callback) { lastlevel = level; let parts = lines[i].split(':'); if (2 === level) { // grafics controller level - if (parts.length > 1 && parts[0].replace(/ +/g, "").toLowerCase().indexOf('chipsetmodel') !== -1) currentController.model = parts[1].trim(); - if (parts.length > 1 && parts[0].replace(/ +/g, "").toLowerCase().indexOf('bus') !== -1) currentController.bus = parts[1].trim(); - if (parts.length > 1 && parts[0].replace(/ +/g, "").toLowerCase().indexOf('vendor') !== -1) currentController.vendor = parts[1].split('(')[0].trim(); - if (parts.length > 1 && parts[0].replace(/ +/g, "").toLowerCase().indexOf('vram(total)') !== -1) { + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('chipsetmodel') !== -1) currentController.model = parts[1].trim(); + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('bus') !== -1) currentController.bus = parts[1].trim(); + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('vendor') !== -1) currentController.vendor = parts[1].split('(')[0].trim(); + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('vram(total)') !== -1) { currentController.vram = parseInt(parts[1]); // in MB currentController.vramDynamic = false; } - if (parts.length > 1 && parts[0].replace(/ +/g, "").toLowerCase().indexOf('vram(dynamic,max)') !== -1) { + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('vram(dynamic,max)') !== -1) { currentController.vram = parseInt(parts[1]); // in MB currentController.vramDynamic = true; } @@ -86,18 +86,18 @@ function graphics(callback) { } } if (4 === level) { // display controller details level - if (parts.length > 1 && parts[0].replace(/ +/g, "").toLowerCase().indexOf('resolution') !== -1) { + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('resolution') !== -1) { let resolution = parts[1].split('x'); currentDisplay.resolutionx = (resolution.length > 1 ? parseInt(resolution[0]) : 0); currentDisplay.resolutiony = (resolution.length > 1 ? parseInt(resolution[1]) : 0); } - if (parts.length > 1 && parts[0].replace(/ +/g, "").toLowerCase().indexOf('pixeldepth') !== -1) currentDisplay.pixeldepth = parseInt(parts[1]); // in BIT - if (parts.length > 1 && parts[0].replace(/ +/g, "").toLowerCase().indexOf('maindisplay') !== -1 && parts[1].replace(/ +/g, "").toLowerCase() === 'yes') currentDisplay.main = true; - if (parts.length > 1 && parts[0].replace(/ +/g, "").toLowerCase().indexOf('built-in') !== -1 && parts[1].replace(/ +/g, "").toLowerCase() === 'yes') { + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('pixeldepth') !== -1) currentDisplay.pixeldepth = parseInt(parts[1]); // in BIT + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('maindisplay') !== -1 && parts[1].replace(/ +/g, '').toLowerCase() === 'yes') currentDisplay.main = true; + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('built-in') !== -1 && parts[1].replace(/ +/g, '').toLowerCase() === 'yes') { currentDisplay.builtin = true; currentDisplay.connection = ''; } - if (parts.length > 1 && parts[0].replace(/ +/g, "").toLowerCase().indexOf('connectiontype') !== -1) { + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('connectiontype') !== -1) { currentDisplay.builtin = false; currentDisplay.connection = parts[1].trim(); } @@ -113,7 +113,7 @@ function graphics(callback) { return ({ controllers: controllers, displays: displays - }) + }); } function parseLinesLinuxControllers(lines) { @@ -145,7 +145,7 @@ function graphics(callback) { currentController.vram = -1; currentController.vramDynamic = false; } else if (parts[1].toLowerCase().indexOf(' inc.') >= 0) { - if ((parts[1].match(new RegExp("]", "g")) || []).length > 1) { + if ((parts[1].match(new RegExp(']', 'g')) || []).length > 1) { currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(']') + 1).trim(); currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']')+1, 200).trim().split('(')[0]; } else { @@ -164,9 +164,9 @@ function graphics(callback) { } if (isGraphicsController) { // within VGA details let parts = lines[i].split(':'); - if (parts.length > 1 && parts[0].replace(/ +/g, "").toLowerCase().indexOf('devicename') !== -1 && parts[0].toLowerCase().indexOf('onboard') !== -1) currentController.bus = 'Onboard'; - if (parts.length > 1 && parts[0].replace(/ +/g, "").toLowerCase().indexOf('region') !== -1 && parts[1].toLowerCase().indexOf('memory') !== -1) { - let memparts = parts[1].split("="); + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('devicename') !== -1 && parts[0].toLowerCase().indexOf('onboard') !== -1) currentController.bus = 'Onboard'; + if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('region') !== -1 && parts[1].toLowerCase().indexOf('memory') !== -1) { + let memparts = parts[1].split('='); if (memparts.length > 1) { currentController.vram = parseInt(memparts[1]); } @@ -177,7 +177,7 @@ function graphics(callback) { if (Object.keys(currentController).length > 0) {// still controller information available controllers.push(currentController); } - return (controllers) + return (controllers); } function parseLinesLinuxEdid(edid) { @@ -213,7 +213,7 @@ function graphics(callback) { if (start >= 0) { let model_raw = edid.substr(start + 10, 26); if (model_raw.indexOf('0a') !== -1) { - model_raw = model_raw.substr(0, model_raw.indexOf('0a')) + model_raw = model_raw.substr(0, model_raw.indexOf('0a')); } result.model = model_raw.match(/.{1,2}/g).map(function (v) { return String.fromCharCode(parseInt(v, 16)); @@ -240,7 +240,7 @@ function graphics(callback) { let parts = lines[i].split(' '); currentDisplay.connection = parts[0]; currentDisplay.main = (parts[2] === 'primary'); - currentDisplay.builtin = (parts[0].toLowerCase().indexOf('edp') >= 0) + currentDisplay.builtin = (parts[0].toLowerCase().indexOf('edp') >= 0); } // try to read EDID information @@ -270,11 +270,11 @@ function graphics(callback) { if (Object.keys(currentDisplay).length > 0) { // still information there displays.push(currentDisplay); } - return displays + return displays; } // function starts here - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = { controllers: [], @@ -288,10 +288,10 @@ function graphics(callback) { result = parseLinesDarwin(lines); } if (callback) { - callback(result) + callback(result); } resolve(result); - }) + }); } if (_linux) { let cmd = 'lspci -vvv 2>/dev/null'; @@ -314,42 +314,42 @@ function graphics(callback) { result.displays = parseLinesLinuxDisplays(lines, depth); } if (callback) { - callback(result) + callback(result); } resolve(result); - }) - }) - }) + }); + }); + }); } if (_windows) { // https://blogs.technet.microsoft.com/heyscriptingguy/2013/10/03/use-powershell-to-discover-multi-monitor-information/ - exec("wmic path win32_VideoController get AdapterCompatibility, AdapterDACType, name, PNPDeviceID, CurrentVerticalResolution, CurrentHorizontalResolution, CurrentNumberOfColors, AdapterRAM, CurrentBitsPerPixel, CurrentRefreshRate, MinRefreshRate, MaxRefreshRate, VideoMemoryType /value", function (error, stdout) { + exec('wmic path win32_VideoController get AdapterCompatibility, AdapterDACType, name, PNPDeviceID, CurrentVerticalResolution, CurrentHorizontalResolution, CurrentNumberOfColors, AdapterRAM, CurrentBitsPerPixel, CurrentRefreshRate, MinRefreshRate, MaxRefreshRate, VideoMemoryType /value', function (error, stdout) { if (!error) { let csections = stdout.split(/\n\s*\n/); result.controllers = parseLinesWindowsControllers(csections); - exec("wmic path win32_desktopmonitor get MonitorManufacturer, ScreenWidth, ScreenHeight /value", function (error, stdout) { + exec('wmic path win32_desktopmonitor get MonitorManufacturer, ScreenWidth, ScreenHeight /value', function (error, stdout) { let dsections = stdout.split(/\n\s*\n/); if (!error) { result.displays = parseLinesWindowsDisplays(dsections); if (result.controllers.length === 1 && result.displays.length === 1) { if (_resolutionx && !result.displays[0].resolutionx) { - result.displays[0].resolutionx = _resolutionx + result.displays[0].resolutionx = _resolutionx; } if (_resolutiony && !result.displays[0].resolutiony) { - result.displays[0].resolutiony = _resolutiony + result.displays[0].resolutiony = _resolutiony; } if (_pixeldepth) { - result.displays[0].pixeldepth = _pixeldepth + result.displays[0].pixeldepth = _pixeldepth; } } } if (callback) { - callback(result) + callback(result); } resolve(result); - }) + }); } - }) + }); } }); }); @@ -358,7 +358,7 @@ function graphics(callback) { let controllers = []; for (let i in sections) { if (sections.hasOwnProperty(i)) { - if (sections[i].trim() !== "") { + if (sections[i].trim() !== '') { let lines = sections[i].trim().split('\r\n'); controllers.push({ @@ -381,7 +381,7 @@ function graphics(callback) { let displays = []; for (let i in sections) { if (sections.hasOwnProperty(i)) { - if (sections[i].trim() !== "") { + if (sections[i].trim() !== '') { let lines = sections[i].trim().split('\r\n'); displays.push({ model: util.getValue(lines, 'MonitorManufacturer', '='), diff --git a/lib/index.js b/lib/index.js index 9b5fc75..845b2bb 100644 --- a/lib/index.js +++ b/lib/index.js @@ -83,8 +83,7 @@ // Dependencies // ---------------------------------------------------------------------------------- -const os = require('os') - , fs = require('fs'); +const os = require('os'); const lib_version = require('../package.json').version; const util = require('./util'); @@ -104,8 +103,6 @@ const docker = require('./docker'); let _platform = os.type(); let _windows = (_platform === 'Windows_NT'); -const NOT_SUPPORTED = 'not supported'; - // ---------------------------------------------------------------------------------- // 1. General // ---------------------------------------------------------------------------------- @@ -123,7 +120,7 @@ function version() { function getStaticData(callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let data = {}; @@ -150,7 +147,7 @@ function getStaticData(callback) { data.net = res[6]; data.memLayout = res[7]; data.diskLayout = res[8]; - if (callback) { callback(data) } + if (callback) { callback(data); } resolve(data); }); }); @@ -176,7 +173,7 @@ function getDynamicData(srv, iface, callback) { srv = ''; } - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { iface = iface || network.getDefaultNetworkInterface(); @@ -189,7 +186,7 @@ function getDynamicData(srv, iface, callback) { return function () { if (--totalFunctions === 0) { if (callback) { - callback(data) + callback(data); } resolve(data); } @@ -308,7 +305,7 @@ function getDynamicData(srv, iface, callback) { function getAllData(srv, iface, callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let data = {}; @@ -320,10 +317,10 @@ function getAllData(srv, iface, callback) { data[key] = res[key]; } } - if (callback) { callback(data) } + if (callback) { callback(data); } resolve(data); }); - }) + }); }); }); } diff --git a/lib/internet.js b/lib/internet.js index 375045f..0bce8d6 100644 --- a/lib/internet.js +++ b/lib/internet.js @@ -21,14 +21,13 @@ let _platform = os.type(); const _linux = (_platform === 'Linux'); const _darwin = (_platform === 'Darwin'); const _windows = (_platform === 'Windows_NT'); -const NOT_SUPPORTED = 'not supported'; // -------------------------- // check if external site is available function inetChecksite(url, callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = { @@ -48,9 +47,9 @@ function inetChecksite(url, callback) { result.status = statusCode || 404; result.ok = !error && (statusCode === 200 || statusCode === 301 || statusCode === 302 || statusCode === 304); result.ms = (result.ok ? Date.now() - t : -1); - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); - }) + }); } if (_windows) { // if this is stable, this can be used for all OS types const http = (url.startsWith('https:') ? require('https') : require('http')); @@ -64,27 +63,27 @@ function inetChecksite(url, callback) { if (statusCode !== 200) { res.resume(); result.ms = (result.ok ? Date.now() - t : -1); - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } else { res.on('data', (chunk) => { }); res.on('end', () => { result.ms = (result.ok ? Date.now() - t : -1); - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }) } }).on('error', err => { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } catch (err) { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } } } else { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } }); @@ -106,9 +105,8 @@ function inetLatency(host, callback) { host = host || '8.8.8.8'; - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { - let t = Date.now(); let cmd; if (_linux || _darwin) { if (_linux) { @@ -123,9 +121,9 @@ function inetLatency(host, callback) { if (!error) { result = parseFloat(stdout.toString()); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); - }) + }); } if (_windows) { exec('ping ' + host + ' -n 1', function (error, stdout) { @@ -135,16 +133,16 @@ function inetLatency(host, callback) { lines.shift(); lines.forEach(function (line) { if (line.toLowerCase().startsWith(' min')) { - let l = line.replace(/ +/g, " ").split(' '); + let l = line.replace(/ +/g, ' ').split(' '); if (l.length > 8) { - result = parseFloat(l[9]) + result = parseFloat(l[9]); } } }); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); - }) + }); } }); }); diff --git a/lib/memory.js b/lib/memory.js index b447def..40b70ec 100644 --- a/lib/memory.js +++ b/lib/memory.js @@ -14,7 +14,6 @@ const os = require('os'); const exec = require('child_process').exec; -const fs = require('fs'); const util = require('./util'); let _platform = os.type(); @@ -22,21 +21,20 @@ let _platform = os.type(); const _linux = (_platform === 'Linux'); const _darwin = (_platform === 'Darwin'); const _windows = (_platform === 'Windows_NT'); -const NOT_SUPPORTED = 'not supported'; const OSX_RAM_manufacturers = { - "0x014F": "Transcend Information", - "0x2C00": "Micron Technology Inc.", - "0x802C": "Micron Technology Inc.", - "0x80AD": "Hynix Semiconductor Inc.", - "0x80CE": "Samsung Electronics Inc.", - "0xAD00": "Hynix Semiconductor Inc.", - "0xCE00": "Samsung Electronics Inc.", - "0x02FE": "Elpida", - "0x5105": "Qimonda AG i. In.", - "0x8551": "Qimonda AG i. In.", - "0x859B": "Crucial" -} + '0x014F': 'Transcend Information', + '0x2C00': 'Micron Technology Inc.', + '0x802C': 'Micron Technology Inc.', + '0x80AD': 'Hynix Semiconductor Inc.', + '0x80CE': 'Samsung Electronics Inc.', + '0xAD00': 'Hynix Semiconductor Inc.', + '0xCE00': 'Samsung Electronics Inc.', + '0x02FE': 'Elpida', + '0x5105': 'Qimonda AG i. In.', + '0x8551': 'Qimonda AG i. In.', + '0x859B': 'Crucial' +}; // _______________________________________________________________________________________ // | R A M | H D | @@ -90,7 +88,7 @@ const OSX_RAM_manufacturers = { function mem(callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = { @@ -108,22 +106,22 @@ function mem(callback) { }; if (_linux) { - exec("free -b", function (error, stdout) { + exec('free -b', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); - let mem = lines[1].replace(/ +/g, " ").split(' '); + let mem = lines[1].replace(/ +/g, ' ').split(' '); result.total = parseInt(mem[1], 10); result.free = parseInt(mem[3], 10); if (lines.length === 4) { // free (since free von procps-ng 3.3.10) result.buffcache = parseInt(mem[5], 10); result.available = parseInt(mem[6], 10); - mem = lines[2].replace(/ +/g, " ").split(' '); + mem = lines[2].replace(/ +/g, ' ').split(' '); } else { // free (older versions) result.buffcache = parseInt(mem[5], 10) + parseInt(mem[6], 10); result.available = result.free + result.buffcache; - mem = lines[3].replace(/ +/g, " ").split(' '); + mem = lines[3].replace(/ +/g, ' ').split(' '); } result.active = result.total - result.free - result.buffcache; @@ -132,7 +130,7 @@ function mem(callback) { result.swapused = parseInt(mem[2], 10); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } @@ -145,21 +143,20 @@ function mem(callback) { result.buffcache = result.used - result.active; result.available = result.free + result.buffcache; } - exec("sysctl -n vm.swapusage", function (error, stdout) { + exec('sysctl -n vm.swapusage', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); if (lines.length > 0) { - let line = lines[0].replace(/,/g, ".").replace(/M/g, ""); + let line = lines[0].replace(/,/g, '.').replace(/M/g, ''); line = line.trim().split(' '); for (let i = 0; i < line.length; i++) { if (line[i].toLowerCase().indexOf('total') !== -1) result.swaptotal = parseFloat(line[i].split('=')[1].trim()) * 1024 * 1024; if (line[i].toLowerCase().indexOf('used') !== -1) result.swapused = parseFloat(line[i].split('=')[1].trim()) * 1024 * 1024; if (line[i].toLowerCase().indexOf('free') !== -1) result.swapfree = parseFloat(line[i].split('=')[1].trim()) * 1024 * 1024; - } } } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); }); @@ -167,7 +164,7 @@ function mem(callback) { if (_windows) { let swaptotal = 0; let swapused = 0; - exec("wmic pagefile get AllocatedBaseSize, CurrentUsage", function (error, stdout) { + exec('wmic pagefile get AllocatedBaseSize, CurrentUsage', function (error, stdout) { if (!error) { let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0); lines.forEach(function (line) { @@ -182,7 +179,7 @@ function mem(callback) { result.swapused = swapused * 1024 * 1024; result.swapfree = result.swaptotal - result.swapused; - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } @@ -196,12 +193,12 @@ function memLayout(callback) { function getManufacturer(manId) { if (OSX_RAM_manufacturers.hasOwnProperty(manId)) { - return(OSX_RAM_manufacturers[manId]) + return(OSX_RAM_manufacturers[manId]); } return manId; } - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = []; @@ -226,7 +223,7 @@ function memLayout(callback) { voltageConfigured: parseFloat(util.getValue(lines, ' Configured Voltage:') || -1), voltageMin: parseFloat(util.getValue(lines, ' Minimum Voltage:') || -1), voltageMax: parseFloat(util.getValue(lines, ' Maximum Voltage:') || -1), - }) + }); } else { result.push({ size: 0, @@ -239,18 +236,17 @@ function memLayout(callback) { voltageConfigured: -1, voltageMin: -1, voltageMax: -1, - }) - + }); } }); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } if (_darwin) { - exec("system_profiler SPMemoryDataType", function (error, stdout) { + exec('system_profiler SPMemoryDataType', function (error, stdout) { if (!error) { let devices = stdout.toString().split(' BANK '); devices.shift(); @@ -271,7 +267,7 @@ function memLayout(callback) { voltageConfigured: -1, voltageMin: -1, voltageMax: -1, - }) + }); } else { result.push({ size: 0, @@ -285,19 +281,19 @@ function memLayout(callback) { voltageConfigured: -1, voltageMin: -1, voltageMax: -1, - }) + }); } }); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } if (_windows) { - const memoryTypes = 'Unknown|Other|DRAM|Synchronous DRAM|Cache DRAM|EDO|EDRAM|VRAM|SRAM|RAM|ROM|FLASH|EEPROM|FEPROM|EPROM|CDRAM|3DRAM|SDRAM|SGRAM|RDRAM|DDR|DDR2|DDR2 FB-DIMM|Reserved|DDR3|FBD2|DDR4|LPDDR|LPDDR2|LPDDR3|LPDDR4'.split('|') + const memoryTypes = 'Unknown|Other|DRAM|Synchronous DRAM|Cache DRAM|EDO|EDRAM|VRAM|SRAM|RAM|ROM|FLASH|EEPROM|FEPROM|EPROM|CDRAM|3DRAM|SDRAM|SGRAM|RDRAM|DDR|DDR2|DDR2 FB-DIMM|Reserved|DDR3|FBD2|DDR4|LPDDR|LPDDR2|LPDDR3|LPDDR4'.split('|'); const FormFactors = 'Unknown|Other|SIP|DIP|ZIP|SOJ|Proprietary|SIMM|DIMM|TSOP|PGA|RIMM|SODIMM|SRIMM|SMD|SSMP|QFP|TQFP|SOIC|LCC|PLCC|BGA|FPBGA|LGA'.split('|'); - exec("wmic memorychip get BankLabel, Capacity, ConfiguredClockSpeed, ConfiguredVoltage, MaxVoltage, MinVoltage, DataWidth, FormFactor, Manufacturer, MemoryType, PartNumber, SerialNumber, Speed, Tag /value", function (error, stdout) { + exec('wmic memorychip get BankLabel, Capacity, ConfiguredClockSpeed, ConfiguredVoltage, MaxVoltage, MinVoltage, DataWidth, FormFactor, Manufacturer, MemoryType, PartNumber, SerialNumber, Speed, Tag /value', function (error, stdout) { if (!error) { let devices = stdout.toString().split('BankL'); devices.shift(); @@ -315,11 +311,10 @@ function memLayout(callback) { voltageConfigured: parseInt(util.getValue(lines, 'ConfiguredVoltage', '='), 10) / 1000.0, voltageMin: parseInt(util.getValue(lines, 'MinVoltage', '='), 10) / 1000.0, voltageMax: parseInt(util.getValue(lines, 'MaxVoltage', '='), 10) / 1000.0, - }) + }); }); } - - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } diff --git a/lib/network.js b/lib/network.js index d2c89fc..5272339 100644 --- a/lib/network.js +++ b/lib/network.js @@ -23,7 +23,6 @@ let _platform = os.type(); const _linux = (_platform === 'Linux'); const _darwin = (_platform === 'Darwin'); const _windows = (_platform === 'Windows_NT'); -const NOT_SUPPORTED = 'not supported'; let _network = {}; let _default_iface; @@ -42,14 +41,6 @@ function getDefaultNetworkInterface() { if (!ifacename) { // fallback - "first" external interface (sorted by scopeid) - const compare = function(a,b) { - if (a.scopeid < b.scopeid) - return -1; - if (a.scopeid > b.scopeid) - return 1; - return 0; - } - let ifaces = os.networkInterfaces(); for (let dev in ifaces) { @@ -59,7 +50,7 @@ function getDefaultNetworkInterface() { ifacename = dev; scopeid = details.scopeid; } - }) + }); } } } @@ -108,15 +99,15 @@ function getMacAddresses() { } } } - return result + return result; } function networkInterfaceDefault(callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = getDefaultNetworkInterface(); - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); }); @@ -141,11 +132,11 @@ function networkInterfaces(callback) { if (ifaces.hasOwnProperty(dev)) { ifaces[dev].forEach(function (details) { if (details.family === 'IPv4') { - ip4 = details.address + ip4 = details.address; } if (details.family === 'IPv6') { if (!ip6 || ip6.match(/^fe80::/i)) { - ip6 = details.address + ip6 = details.address; } } mac = details.mac; @@ -157,10 +148,10 @@ function networkInterfaces(callback) { } }); let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : null; - result.push({ iface: dev, ip4: ip4, ip6: ip6, mac: mac, internal: internal }) + result.push({ iface: dev, ip4: ip4, ip6: ip6, mac: mac, internal: internal }); } } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); }); @@ -210,14 +201,14 @@ function networkStats(iface, callback) { let nics = []; for (let i in sections) { if (sections.hasOwnProperty(i)) { - if (sections[i].trim() !== "") { + if (sections[i].trim() !== '') { let lines = sections[i].trim().split('\r\n'); let netEnabled = util.getValue(lines, 'NetEnabled', '='); if (netEnabled) { nics.push({ mac: util.getValue(lines, 'MACAddress', '=').toLowerCase(), - name: util.getValue(lines, 'Name', '=').replace(/[()\[\] ]+/g, "").toLowerCase(), + name: util.getValue(lines, 'Name', '=').replace(/[()\[\] ]+/g, '').toLowerCase(), netEnabled: netEnabled === 'TRUE' }); } @@ -231,11 +222,11 @@ function networkStats(iface, callback) { let perfData = []; for (let i in sections) { if (sections.hasOwnProperty(i)) { - if (sections[i].trim() !== "") { + if (sections[i].trim() !== '') { let lines = sections[i].trim().split('\r\n'); perfData.push({ - name: util.getValue(lines, 'Name', '=').replace(/[()\[\] ]+/g, "").toLowerCase(), + name: util.getValue(lines, 'Name', '=').replace(/[()\[\] ]+/g, '').toLowerCase(), rx: parseInt(util.getValue(lines, 'BytesReceivedPersec', '='),10), tx: parseInt(util.getValue(lines, 'BytesSentPersec', '='),10) }); @@ -252,7 +243,7 @@ function networkStats(iface, callback) { iface = ''; } - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { _default_iface = _default_iface || getDefaultNetworkInterface(); @@ -277,9 +268,9 @@ function networkStats(iface, callback) { if (_linux) { if (fs.existsSync('/sys/class/net/' + iface)) { cmd = - "cat /sys/class/net/" + iface + "/operstate; " + - "cat /sys/class/net/" + iface + "/statistics/rx_bytes; " + - "cat /sys/class/net/" + iface + "/statistics/tx_bytes; "; + 'cat /sys/class/net/' + iface + '/operstate; ' + + 'cat /sys/class/net/' + iface + '/statistics/rx_bytes; ' + + 'cat /sys/class/net/' + iface + '/statistics/tx_bytes; '; exec(cmd, function (error, stdout) { if (!error) { lines = stdout.toString().split('\n'); @@ -290,11 +281,11 @@ function networkStats(iface, callback) { result = calcNetworkSpeed(iface, rx, tx, operstate); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } else { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } } @@ -304,7 +295,7 @@ function networkStats(iface, callback) { result.operstate = (stdout.toString().split(':')[1] || '').trim(); result.operstate = (result.operstate || '').toLowerCase(); result.operstate = (result.operstate === 'active' ? 'up' : (result.operstate === 'inactive' ? 'down' : 'unknown')); - cmd = "netstat -bI " + iface; + cmd = 'netstat -bI ' + iface; exec(cmd, function (error, stdout) { if (!error) { lines = stdout.toString().split('\n'); @@ -312,14 +303,14 @@ function networkStats(iface, callback) { if (lines.length > 1 && lines[1].trim() !== '') { // skip header line // use the second line because it is tied to the NIC instead of the ipv4 or ipv6 address - stats = lines[1].replace(/ +/g, " ").split(' '); + stats = lines[1].replace(/ +/g, ' ').split(' '); rx = parseInt(stats[6]); tx = parseInt(stats[9]); result = calcNetworkSpeed(iface, rx, tx, operstate); } } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); }); @@ -328,14 +319,14 @@ function networkStats(iface, callback) { // NICs let perfData = []; let nics = []; - cmd = "wmic nic get MACAddress, name, NetEnabled /value"; + cmd = 'wmic nic get MACAddress, name, NetEnabled /value'; exec(cmd, function (error, stdout) { if (!error) { const nsections = stdout.split(/\n\s*\n/); nics = parseLinesWindowsNics(nsections); // Performance Data - cmd = "wmic path Win32_PerfRawData_Tcpip_NetworkInterface Get name,BytesReceivedPersec,BytesSentPersec,BytesTotalPersec /value"; + cmd = 'wmic path Win32_PerfRawData_Tcpip_NetworkInterface Get name,BytesReceivedPersec,BytesSentPersec,BytesTotalPersec /value'; exec(cmd, function (error, stdout) { if (!error) { const psections = stdout.split(/\n\s*\n/); @@ -350,16 +341,16 @@ function networkStats(iface, callback) { if (detail.iface === iface) { mac = detail.mac; } - }) + }); // get name from 'nics' (by macadress) let name = ''; nics.forEach(detail => { if (detail.mac === mac) { name = detail.name; - operstate = (detail.netEnabled ? 'up' : 'down') + operstate = (detail.netEnabled ? 'up' : 'down'); } - }) + }); // get bytes sent, received from perfData by name rx = 0; @@ -374,10 +365,10 @@ function networkStats(iface, callback) { if (rx && tx) { result = calcNetworkSpeed(iface, parseInt(rx), parseInt(tx), operstate); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); - }) - }) + }); + }); } }); } @@ -387,7 +378,7 @@ function networkStats(iface, callback) { result.rx_sec = _network[iface].rx_sec; result.tx_sec = _network[iface].tx_sec; result.ms = _network[iface].last_ms; - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } }); @@ -401,7 +392,7 @@ exports.networkStats = networkStats; function networkConnections(callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = []; if (_linux) { @@ -410,7 +401,7 @@ function networkConnections(callback) { if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { - line = line.replace(/ +/g, " ").split(' '); + line = line.replace(/ +/g, ' ').split(' '); if (line.length >= 6) { let localip = line[3]; let localport = ''; @@ -438,12 +429,12 @@ function networkConnections(callback) { peeraddress: peerip, peerport: peerport, state: connstate - }) + }); } } }); if (callback) { - callback(result) + callback(result); } resolve(result); } else { @@ -453,7 +444,7 @@ function networkConnections(callback) { if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { - line = line.replace(/ +/g, " ").split(' '); + line = line.replace(/ +/g, ' ').split(' '); if (line.length >= 6) { let localip = line[4]; let localport = ''; @@ -482,18 +473,18 @@ function networkConnections(callback) { peeraddress: peerip, peerport: peerport, state: connstate - }) + }); } } }); } if (callback) { - callback(result) + callback(result); } resolve(result); - }) + }); } - }) + }); } if (_darwin) { let cmd = "netstat -nat | grep 'ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN'"; @@ -503,7 +494,7 @@ function networkConnections(callback) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { - line = line.replace(/ +/g, " ").split(' '); + line = line.replace(/ +/g, ' ').split(' '); if (line.length >= 6) { let localip = line[3]; let localport = ''; @@ -530,26 +521,26 @@ function networkConnections(callback) { peeraddress: peerip, peerport: peerport, state: connstate - }) + }); } } }); if (callback) { - callback(result) + callback(result); } resolve(result); } - }) + }); } if (_windows) { - let cmd = "netstat -na"; + let cmd = 'netstat -na'; exec(cmd, function (error, stdout) { if (!error) { let lines = stdout.toString().split('\r\n'); lines.forEach(function (line) { - line = line.trim().replace(/ +/g, " ").split(' '); + line = line.trim().replace(/ +/g, ' ').split(' '); if (line.length >= 4) { let localip = line[1]; let localport = ''; @@ -586,16 +577,16 @@ function networkConnections(callback) { peeraddress: peerip, peerport: peerport, state: connstate - }) + }); } } }); if (callback) { - callback(result) + callback(result); } resolve(result); } - }) + }); } }); }); diff --git a/lib/osinfo.js b/lib/osinfo.js index fdf10a5..b032f59 100644 --- a/lib/osinfo.js +++ b/lib/osinfo.js @@ -14,8 +14,6 @@ const os = require('os'); const exec = require('child_process').exec; -const fs = require('fs'); -const util = require('./util'); let _platform = os.type(); @@ -48,88 +46,91 @@ function getLogoFile(distro) { distro = distro.toLowerCase(); let result = 'linux'; if (_windows) { - result = 'windows' + result = 'windows'; } else if (distro.indexOf('mac os') !== -1) { - result = 'apple' + result = 'apple'; } else if (distro.indexOf('arch') !== -1) { - result = 'arch' + result = 'arch'; } else if (distro.indexOf('centos') !== -1) { - result = 'centos' + result = 'centos'; } else if (distro.indexOf('coreos') !== -1) { - result = 'coreos' + result = 'coreos'; } else if (distro.indexOf('debian') !== -1) { - result = 'debian' + result = 'debian'; + } + else if (distro.indexOf('deepin') !== -1) { + result = 'deepin'; } else if (distro.indexOf('elementary') !== -1) { - result = 'elementary' + result = 'elementary'; } else if (distro.indexOf('fedora') !== -1) { - result = 'fedora' + result = 'fedora'; } else if (distro.indexOf('gentoo') !== -1) { - result = 'gentoo' + result = 'gentoo'; } else if (distro.indexOf('mageia') !== -1) { - result = 'mageia' + result = 'mageia'; } else if (distro.indexOf('mandriva') !== -1) { - result = 'mandriva' + result = 'mandriva'; } else if (distro.indexOf('manjaro') !== -1) { - result = 'manjaro' + result = 'manjaro'; } else if (distro.indexOf('mint') !== -1) { - result = 'mint' + result = 'mint'; } else if (distro.indexOf('openbsd') !== -1) { - result = 'openbsd' + result = 'openbsd'; } else if (distro.indexOf('opensuse') !== -1) { - result = 'opensuse' + result = 'opensuse'; } else if (distro.indexOf('pclinuxos') !== -1) { - result = 'pclinuxos' + result = 'pclinuxos'; } else if (distro.indexOf('puppy') !== -1) { - result = 'puppy' + result = 'puppy'; } else if (distro.indexOf('raspbian') !== -1) { - result = 'raspbian' + result = 'raspbian'; } else if (distro.indexOf('reactos') !== -1) { - result = 'reactos' + result = 'reactos'; } else if (distro.indexOf('redhat') !== -1) { - result = 'redhat' + result = 'redhat'; } else if (distro.indexOf('slackware') !== -1) { - result = 'slackware' + result = 'slackware'; } else if (distro.indexOf('sugar') !== -1) { - result = 'sugar' + result = 'sugar'; } else if (distro.indexOf('steam') !== -1) { - result = 'steam' + result = 'steam'; } else if (distro.indexOf('suse') !== -1) { - result = 'suse' + result = 'suse'; } else if (distro.indexOf('mate') !== -1) { - result = 'ubuntu-mate' + result = 'ubuntu-mate'; } else if (distro.indexOf('lubuntu') !== -1) { - result = 'lubuntu' + result = 'lubuntu'; } else if (distro.indexOf('xubuntu') !== -1) { - result = 'xubuntu' + result = 'xubuntu'; } else if (distro.indexOf('ubuntu') !== -1) { - result = 'ubuntu' + result = 'ubuntu'; } return result; } @@ -155,7 +156,7 @@ function osInfo(callback) { if (_linux) { - exec("cat /etc/*-release", function (error, stdout) { + exec('cat /etc/*-release', function (error, stdout) { //if (!error) { /** * @namespace @@ -178,13 +179,13 @@ function osInfo(callback) { result.codename = (release.DISTRIB_CODENAME || '').replace(/"/g, ''); //} if (callback) { - callback(result) + callback(result); } resolve(result); - }) + }); } if (_darwin) { - exec("sw_vers", function (error, stdout) { + exec('sw_vers', function (error, stdout) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { if (line.indexOf('ProductName') !== -1) { @@ -194,18 +195,18 @@ function osInfo(callback) { if (line.indexOf('ProductVersion') !== -1) result.release = line.split(':')[1].trim(); }); if (callback) { - callback(result) + callback(result); } resolve(result); - }) + }); } if (_windows) { result.logofile = getLogoFile(); result.release = result.kernel; - exec("wmic os get Caption", function (error, stdout) { + exec('wmic os get Caption', function (error, stdout) { result.distro = result.codename = stdout.slice(stdout.indexOf('\r\n') + 2).trim(); if (callback) { - callback(result) + callback(result); } resolve(result); }); @@ -233,44 +234,44 @@ function versions(callback) { tsc: '', }; let parts = []; - exec("npm -v", function (error, stdout) { + exec('npm -v', function (error, stdout) { if (!error) { result.npm = stdout.toString().split('\n')[0]; } - exec("pm2 -v", function (error, stdout) { + exec('pm2 -v', function (error, stdout) { if (!error) { parts = stdout.toString().split('\n'); if (parts.length >= 2) { result.pm2 = parts[parts.length - 2]; } } - exec("yarn --version", function (error, stdout) { + exec('yarn --version', function (error, stdout) { if (!error) { result.yarn = stdout.toString().split('\n')[0]; } - exec("gulp --version", function (error, stdout) { + exec('gulp --version', function (error, stdout) { if (!error) { result.gulp = stdout.toString().split('\n')[0] || ''; result.gulp = (result.gulp.toLowerCase().split('version')[1] || '').trim(); } - exec("tsc --version", function (error, stdout) { + exec('tsc --version', function (error, stdout) { if (!error) { result.tsc = stdout.toString().split('\n')[0] || ''; result.tsc = (result.tsc.toLowerCase().split('version')[1] || '').trim(); } - exec("grunt --version", function (error, stdout) { + exec('grunt --version', function (error, stdout) { if (!error) { result.grunt = stdout.toString().split('\n')[0] || ''; result.grunt = (result.grunt.toLowerCase().split('cli v')[1] || '').trim(); } - exec("git --version", function (error, stdout) { + exec('git --version', function (error, stdout) { if (!error) { result.git = stdout.toString().split('\n')[0] || ''; result.git = (result.git.toLowerCase().split('version')[1] || '').trim(); result.git = (result.git.split(' ')[0] || '').trim(); } if (callback) { - callback(result) + callback(result); } resolve(result); }); @@ -292,18 +293,18 @@ function shell(callback) { if (_windows) { let error = new Error(NOT_SUPPORTED); if (callback) { - callback(NOT_SUPPORTED) + callback(NOT_SUPPORTED); } reject(error); } let result = ''; - exec("echo $SHELL", function (error, stdout) { + exec('echo $SHELL', function (error, stdout) { if (!error) { result = stdout.toString().split('\n')[0]; } if (callback) { - callback(result) + callback(result); } resolve(result); }); diff --git a/lib/processes.js b/lib/processes.js index b24b04d..54901c8 100644 --- a/lib/processes.js +++ b/lib/processes.js @@ -14,7 +14,6 @@ const os = require('os'); const exec = require('child_process').exec; -const fs = require('fs'); const util = require('./util'); let _platform = os.type(); @@ -42,13 +41,13 @@ let _winStatusValues = { '7': 'terminated', '8': 'stopped', '9': 'growing', -} +}; function parseTimeWin(time) { time = time || ''; if (time) { - return (time.substr(0,4) + '-' + time.substr(4,2) + '-' + time.substr(6,2) + ' ' + time.substr(8,2) + ':' + time.substr(10,2) + ':' + time.substr(12,2)) + return (time.substr(0,4) + '-' + time.substr(4,2) + '-' + time.substr(6,2) + ' ' + time.substr(8,2) + ':' + time.substr(10,2) + ':' + time.substr(12,2)); } else { return ''; } @@ -68,22 +67,22 @@ function services(srv, callback) { srv = ''; } - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { - srv = srv.trim().toLowerCase().replace(/,+/g, " ").replace(/ +/g, " ").replace(/ +/g, "|"); + srv = srv.trim().toLowerCase().replace(/,+/g, ' ').replace(/ +/g, ' ').replace(/ +/g, '|'); let srvs = srv.split('|'); let data = []; let dataSrv = []; if (_linux || _darwin) { - let comm = (_darwin) ? "ps -caxm -o pcpu,pmem,comm" : "ps axo pcpu,pmem,comm"; + let comm = (_darwin) ? 'ps -caxm -o pcpu,pmem,comm' : 'ps axo pcpu,pmem,comm'; if (srv !== '' && srvs.length > 0) { exec(comm + " | grep -v grep | egrep '" + srv + "'", function (error, stdout) { if (!error) { - let lines = stdout.toString().replace(/ +/g, " ").replace(/,+/g, ".").split('\n'); + let lines = stdout.toString().replace(/ +/g, ' ').replace(/,+/g, '.').split('\n'); srvs.forEach(function (srv) { let ps = lines.filter(function (e) { - return e.indexOf(srv) !== -1 + return e.indexOf(srv) !== -1; }); data.push({ 'name': srv, @@ -94,9 +93,9 @@ function services(srv, callback) { 'pmem': parseFloat((ps.reduce(function (pv, cv) { return pv + parseFloat(cv.trim().split(' ')[1]); }, 0)).toFixed(2)) - }) + }); }); - if (callback) { callback(data) } + if (callback) { callback(data); } resolve(data); } else { srvs.forEach(function (srv) { @@ -105,23 +104,23 @@ function services(srv, callback) { 'running': false, 'pcpu': 0, 'pmem': 0 - }) + }); }); - if (callback) { callback(data) } + if (callback) { callback(data); } resolve(data); } }); } else { - if (callback) { callback(data) } + if (callback) { callback(data); } resolve(data); } } if (_windows) { - exec("wmic service get /value", {maxBuffer: 1024 * 1000}, function (error, stdout) { + exec('wmic service get /value', {maxBuffer: 1024 * 1000}, function (error, stdout) { if (!error) { let serviceSections = stdout.split(/\n\s*\n/); for (let i = 0; i < serviceSections.length; i++) { - if (serviceSections[i].trim() !== "") { + if (serviceSections[i].trim() !== '') { let lines = serviceSections[i].trim().split('\r\n'); let srv = util.getValue(lines, 'Name', '=', true).toLowerCase(); let started = util.getValue(lines, 'Started', '=', true); @@ -131,13 +130,13 @@ function services(srv, callback) { 'running': (started === 'TRUE'), 'pcpu': 0, 'pmem': 0 - }) + }); dataSrv.push(srv); } } } let srvsMissing = srvs.filter(function (e) { - return dataSrv.indexOf(e) === -1 + return dataSrv.indexOf(e) === -1; }); srvsMissing.forEach(function (srv) { data.push({ @@ -145,10 +144,10 @@ function services(srv, callback) { 'running': false, 'pcpu': 0, 'pmem': 0 - }) + }); }); - if (callback) { callback(data) } + if (callback) { callback(data); } resolve(data); } else { srvs.forEach(function (srv) { @@ -157,12 +156,12 @@ function services(srv, callback) { 'running': false, 'pcpu': 0, 'pmem': 0 - }) + }); }); - if (callback) { callback(data) } + if (callback) { callback(data); } resolve(data); } - }) + }); } }); }); @@ -241,18 +240,15 @@ function processes(callback) { function checkColumn(i) { offset = offset2; - offset2 = line.substring(parsedhead[i].to + offset, 1000).indexOf(' ') -// if (line.substring(parsedhead[i].to + offset, parsedhead[i].to + offset + 1) !== ' ') { -// offset2++; -// } + offset2 = line.substring(parsedhead[i].to + offset, 1000).indexOf(' '); } checkColumn(0); let pid = parseInt(line.substring(parsedhead[0].from + offset, parsedhead[0].to + offset2)); checkColumn(1); - let pcpu = parseFloat(line.substring(parsedhead[1].from + offset, parsedhead[1].to + offset2).replace(/,/g, ".")); + let pcpu = parseFloat(line.substring(parsedhead[1].from + offset, parsedhead[1].to + offset2).replace(/,/g, '.')); checkColumn(2); - let pmem = parseFloat(line.substring(parsedhead[2].from + offset, parsedhead[2].to + offset2).replace(/,/g, ".")); + let pmem = parseFloat(line.substring(parsedhead[2].from + offset, parsedhead[2].to + offset2).replace(/,/g, '.')); checkColumn(3); let priority = parseInt(line.substring(parsedhead[3].from + offset, parsedhead[3].to + offset2)); checkColumn(4); @@ -272,7 +268,7 @@ function processes(callback) { checkColumn(10); let user = line.substring(parsedhead[10].from + offset, parsedhead[10].to + offset2).trim(); checkColumn(11); - let command = line.substring(parsedhead[11].from + offset, parsedhead[11].to + offset2).trim().replace(/\[/g, "").replace(/]/g, ""); + let command = line.substring(parsedhead[11].from + offset, parsedhead[11].to + offset2).trim().replace(/\[/g, '').replace(/]/g, ''); return ({ pid: pid, @@ -290,7 +286,7 @@ function processes(callback) { tty: tty, user: user, command: command - }) + }); } function parseProcesses(lines) { @@ -309,7 +305,7 @@ function processes(callback) { } function parseProcStat(line) { - let parts = line.replace(/ +/g, " ").split(' '); + 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); @@ -324,7 +320,7 @@ function processes(callback) { } function parseProcPidStat(line, all) { - let statparts = line.replace(/ +/g, " ").split(')'); + let statparts = line.replace(/ +/g, ' ').split(')'); if (statparts.length >= 2) { let parts = statparts[1].split(' '); if (parts.length >= 16) { @@ -352,7 +348,7 @@ function processes(callback) { cstime: cstime, pcpuu: pcpuu, pcpus: pcpus - } + }; } else { return { pid: 0, @@ -362,7 +358,7 @@ function processes(callback) { cstime: 0, pcpuu: 0, pcpus: 0 - } + }; } } else { return { @@ -373,7 +369,7 @@ function processes(callback) { cstime: 0, pcpuu: 0, pcpus: 0 - } + }; } } @@ -394,10 +390,10 @@ function processes(callback) { stime: procStat.stime, pcpuu: pcpuu, pcpus: pcpus - } + }; } - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = { all: 0, @@ -408,31 +404,31 @@ function processes(callback) { list: [] }; - let cmd = ""; + let cmd = ''; if ((_process_cpu.ms && Date.now() - _process_cpu.ms >= 500) || _process_cpu.ms === 0) { if (_linux || _darwin) { - if (_linux) cmd = "ps axo pid:10,pcpu:6,pmem:6,pri:5,vsz:10,rss:10,ni:5,start:20,state:20,tty:20,user:20,command"; - if (_darwin) cmd = "ps acxo pid,pcpu,pmem,pri,vsz,rss,nice,start,state,tty,user,command -r"; + if (_linux) cmd = 'ps axo pid:10,pcpu:6,pmem:6,pri:5,vsz:10,rss:10,ni:5,start:20,state:20,tty:20,user:20,command'; + if (_darwin) cmd = 'ps acxo pid,pcpu,pmem,pri,vsz,rss,nice,start,state,tty,user,command -r'; exec(cmd, function (error, stdout) { if (!error) { result.list = parseProcesses(stdout.toString().split('\n')); result.all = result.list.length; result.running = result.list.filter(function (e) { - return e.state === 'running' + return e.state === 'running'; }).length; result.blocked = result.list.filter(function (e) { - return e.state === 'blocked' + return e.state === 'blocked'; }).length; result.sleeping = result.list.filter(function (e) { - return e.state === 'sleeping' + return e.state === 'sleeping'; }).length; if (_linux) { // calc process_cpu - ps is not accurate in linux! cmd = "cat /proc/stat | grep 'cpu '"; for (let i = 0; i < result.list.length; i++) { - cmd += (';cat /proc/' + result.list[i].pid + '/stat') + cmd += (';cat /proc/' + result.list[i].pid + '/stat'); } exec(cmd, function (error, stdout) { let curr_processes = stdout.toString().split('\n'); @@ -464,7 +460,7 @@ function processes(callback) { stime: resultProcess.stime, cutime: resultProcess.cutime, cstime: resultProcess.cstime - } + }; } } @@ -473,18 +469,18 @@ function processes(callback) { _process_cpu.list = list_new; _process_cpu.ms = Date.now() - _process_cpu.ms; _process_cpu.result = result; - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); - }) + }); } else { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } } }); } if (_windows) { - exec("wmic process get /value", {maxBuffer: 1024 * 1000}, function (error, stdout) { + exec('wmic process get /value', {maxBuffer: 1024 * 1000}, function (error, stdout) { if (!error) { let processSections = stdout.split(/\n\s*\n/); let procs = []; @@ -493,10 +489,10 @@ function processes(callback) { let allcpuu = 0; let allcpus = 0; for (let i = 0; i < processSections.length; i++) { - if (processSections[i].trim() !== "") { + if (processSections[i].trim() !== '') { let lines = processSections[i].trim().split('\r\n'); let pid = parseInt(util.getValue(lines, 'ProcessId', '=', true), 10); - let statusValue = util.getValue(lines, 'ExecutionState', '=') + let statusValue = util.getValue(lines, 'ExecutionState', '='); let name = util.getValue(lines, 'Caption', '=', true); let commandLine = util.getValue(lines, 'CommandLine', '=', true); let utime = parseInt(util.getValue(lines, 'UserModeTime', '=', true), 10); @@ -505,9 +501,9 @@ function processes(callback) { allcpuu = allcpuu + utime; allcpus = allcpus + stime; result.all++; - if (!statusValue) { result.unknown++} - if (statusValue === '3') { result.running++} - if (statusValue === '4' || statusValue === '5') { result.blocked++} + if (!statusValue) { result.unknown++; } + if (statusValue === '3') { result.running++; } + if (statusValue === '4' || statusValue === '5') { result.blocked++; } procStats.push({ pid: pid, @@ -555,7 +551,7 @@ function processes(callback) { pcpus: resultProcess.pcpus, utime: resultProcess.utime, stime: resultProcess.stime - } + }; } // store old values _process_cpu.all = allcpuu + allcpus; @@ -564,13 +560,13 @@ function processes(callback) { _process_cpu.result = result; } if (callback) { - callback(result) + callback(result); } resolve(result); - }) + }); } } else { - if (callback) { callback(_process_cpu.result) } + if (callback) { callback(_process_cpu.result); } resolve(_process_cpu.result); } }); @@ -596,7 +592,7 @@ function processLoad(proc, callback) { process.nextTick(() => { if (_windows) { let error = new Error(NOT_SUPPORTED); - if (callback) { callback(NOT_SUPPORTED) } + if (callback) { callback(NOT_SUPPORTED); } reject(error); } @@ -608,9 +604,9 @@ function processLoad(proc, callback) { }; if (proc) { - exec("ps aux | grep " + proc + " | grep -v grep", function (error, stdout) { + exec('ps aux | grep ' + proc + ' | grep -v grep', function (error, stdout) { if (!error) { - let data = stdout.replace(/ +/g, " ").split(' '); + let data = stdout.replace(/ +/g, ' ').split(' '); if (data.length > 2) { result = { @@ -618,14 +614,14 @@ function processLoad(proc, callback) { 'pid': data[1], 'cpu': parseFloat(data[2].replace(',', '.')), 'mem': parseFloat(data[3].replace(',', '.')) - } + }; } } - 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/system.js b/lib/system.js index 4b7b8ef..2759635 100644 --- a/lib/system.js +++ b/lib/system.js @@ -15,18 +15,16 @@ const os = require('os'); const exec = require('child_process').exec; const fs = require('fs'); -const util = require('./util'); let _platform = os.type(); const _linux = (_platform === 'Linux'); const _darwin = (_platform === 'Darwin'); const _windows = (_platform === 'Windows_NT'); -const NOT_SUPPORTED = 'not supported'; module.exports = function (callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = { @@ -38,7 +36,7 @@ module.exports = function (callback) { }; if (_linux) { - exec("dmidecode -t system", function (error, stdout) { + exec('dmidecode -t system', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { @@ -57,7 +55,7 @@ module.exports = function (callback) { if (result.manufacturer === '' && result.model === 'Computer' && result.version === '-') { // Check Raspberry Pi - exec("grep Hardware /proc/cpuinfo; grep Serial /proc/cpuinfo; grep Revision /proc/cpuinfo", function (error, stdout) { + exec('grep Hardware /proc/cpuinfo; grep Serial /proc/cpuinfo; grep Revision /proc/cpuinfo', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { @@ -71,14 +69,14 @@ module.exports = function (callback) { result.manufacturer = 'Raspberry Pi Foundation'; result.model = result.model + ' - Pi 3 Model B'; if (['a02082', 'a22082', 'a32082'].indexOf(result.version) >= 0) { - result.version = result.version + ' - Rev. 1.2' + result.version = result.version + ' - Rev. 1.2'; } } if (result.model === 'BCM2709') { // Pi 2 result.manufacturer = 'Raspberry Pi Foundation'; result.model = result.model + ' - Pi 2 Model B'; if (['a01041', 'a21041'].indexOf(result.version) >= 0) { - result.version = result.version + ' - Rev. 1.1' + result.version = result.version + ' - Rev. 1.1'; } } if (result.model === 'BCM2708') { // Pi, Pi Zero @@ -121,34 +119,34 @@ module.exports = function (callback) { } } } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); - }) + }); } else { - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); } } else { exec("dmesg | grep -i virtual | grep -iE 'vmware|qemu|kvm|xen'", function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); - if (lines.length > 0) result.model = 'Virtual machine' + if (lines.length > 0) result.model = 'Virtual machine'; } if (fs.existsSync('/.dockerenv') || fs.existsSync('/.dockerinit')) { - result.model = 'Docker Container' + result.model = 'Docker Container'; } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } - }) + }); } if (_darwin) { - exec("ioreg -c IOPlatformExpertDevice -d 2", function (error, stdout) { + exec('ioreg -c IOPlatformExpertDevice -d 2', function (error, stdout) { if (!error) { let lines = stdout.toString().split('\n'); lines.forEach(function (line) { - line = line.replace(/[<>"]/g, ""); + line = line.replace(/[<>"]/g, ''); if (line.indexOf('=') !== -1) { if (line.toLowerCase().indexOf('manufacturer') !== -1) result.manufacturer = line.split('=')[1].trim(); if (line.toLowerCase().indexOf('model') !== -1) result.model = line.split('=')[1].trim(); @@ -158,12 +156,12 @@ module.exports = function (callback) { } }); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); - }) + }); } if (_windows) { - exec("wmic csproduct get", function (error, stdout) { + exec('wmic csproduct get', function (error, stdout) { if (!error) { let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0)[0].trim().split(/\s\s+/); result.manufacturer = lines[5]; @@ -172,9 +170,9 @@ module.exports = function (callback) { result.serial = lines[2]; result.uuid = lines[4]; } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); - }) + }); } }); }); diff --git a/lib/users.js b/lib/users.js index e6fb69d..aa39d23 100644 --- a/lib/users.js +++ b/lib/users.js @@ -14,14 +14,12 @@ const os = require('os'); const exec = require('child_process').exec; -const util = require('./util'); let _platform = os.type(); const _linux = (_platform === 'Linux'); const _darwin = (_platform === 'Darwin'); const _windows = (_platform === 'Windows_NT'); -const NOT_SUPPORTED = 'not supported'; // -------------------------- // array of users online = sessions @@ -33,7 +31,6 @@ function parseUsersLinux(lines) { let w_first = true; let w_header = []; let w_pos = []; - let w_headerline = ''; let who_line = {}; let is_whopart = true; @@ -41,7 +38,7 @@ function parseUsersLinux(lines) { if (line === '---') { is_whopart = false; } else { - let l = line.replace(/ +/g, " ").split(' '); + let l = line.replace(/ +/g, ' ').split(' '); // who part if (is_whopart) { @@ -50,26 +47,25 @@ function parseUsersLinux(lines) { tty: l[1], date: l[2], time: l[3], - ip: (l && l.length > 4) ? l[4].replace(/\(/g, "").replace(/\)/g, "") : '' - }) + ip: (l && l.length > 4) ? l[4].replace(/\(/g, '').replace(/\)/g, '') : '' + }); } else { // w part if (w_first) { // header w_header = l; - w_headerline = line; w_header.forEach(function (item) { - w_pos.push(line.indexOf(item)) + w_pos.push(line.indexOf(item)); }); w_first = false; } else { // split by w_pos result_w.user = line.substring(w_pos[0], w_pos[1] - 1).trim(); result_w.tty = line.substring(w_pos[1], w_pos[2] - 1).trim(); - result_w.ip = line.substring(w_pos[2], w_pos[3] - 1).replace(/\(/g, "").replace(/\)/g, "").trim(); + result_w.ip = line.substring(w_pos[2], w_pos[3] - 1).replace(/\(/g, '').replace(/\)/g, '').trim(); result_w.command = line.substring(w_pos[7], 1000).trim(); // find corresponding 'who' line who_line = result_who.filter(function (obj) { - return (obj.user.substring(0, 8).trim() === result_w.user && obj.tty === result_w.tty) + return (obj.user.substring(0, 8).trim() === result_w.user && obj.tty === result_w.tty); }); if (who_line.length === 1) { result.push({ @@ -79,7 +75,7 @@ function parseUsersLinux(lines) { time: who_line[0].time, ip: who_line[0].ip, command: result_w.command - }) + }); } } } @@ -99,16 +95,16 @@ function parseUsersDarwin(lines) { if (line === '---') { is_whopart = false; } else { - let l = line.replace(/ +/g, " ").split(' '); + let l = line.replace(/ +/g, ' ').split(' '); // who part if (is_whopart) { result_who.push({ user: l[0], tty: l[1], - date: ("" + new Date().getFullYear()) + '-' + ("0" + ("JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC".indexOf(l[2].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ("0" + l[3]).slice(-2), + date: ('' + new Date().getFullYear()) + '-' + ('0' + ('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.indexOf(l[2].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ('0' + l[3]).slice(-2), time: l[4], - }) + }); } else { // w part // split by w_pos @@ -118,7 +114,7 @@ function parseUsersDarwin(lines) { result_w.command = l.slice(5, 1000).join(' '); // find corresponding 'who' line who_line = result_who.filter(function (obj) { - return (obj.user === result_w.user && (obj.tty.substring(3, 1000) === result_w.tty || obj.tty === result_w.tty)) + return (obj.user === result_w.user && (obj.tty.substring(3, 1000) === result_w.tty || obj.tty === result_w.tty)); }); if (who_line.length === 1) { result.push({ @@ -128,7 +124,7 @@ function parseUsersDarwin(lines) { time: who_line[0].time, ip: result_w.ip, command: result_w.command - }) + }); } } } @@ -142,28 +138,28 @@ function parseUsersWin(lines) { const result = { date: '', time: '' - } + }; const parts = dt.split(' '); if (parts[0]) { if (parts[0].indexOf('/') >= 0) { // Dateformat: mm/dd/yyyy const dtparts = parts[0].split('/'); if (dtparts.length === 3) { - result.date = dtparts[2] + '-' + ('0' + dtparts[0]).substr(-2) + '-' + ('0' + dtparts[1]).substr(-2) + result.date = dtparts[2] + '-' + ('0' + dtparts[0]).substr(-2) + '-' + ('0' + dtparts[1]).substr(-2); } } if (parts[0].indexOf('.') >= 0) { // Dateformat: dd.mm.yyyy const dtparts = parts[0].split('.'); if (dtparts.length === 3) { - result.date = dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2) + result.date = dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2); } } if (parts[0].indexOf('-') >= 0) { // Dateformat: yyyy-mm-dd const dtparts = parts[0].split('-'); if (dtparts.length === 3) { - result.date = dtparts[0] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[2]).substr(-2) + result.date = dtparts[0] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[2]).substr(-2); } } } @@ -179,7 +175,7 @@ function parseUsersWin(lines) { if (header) { const start = (header[0] === ' ') ? 1 : 0; headerDelimiter.push(start-1); - let nextSpace = 0 + let nextSpace = 0; for (let i = start+1; i < header.length; i++) { if (header[i] === ' ' && header[i-1] === ' ') { nextSpace = i; @@ -203,7 +199,7 @@ function parseUsersWin(lines) { time: dateTime.time, ip: '', command: '' - }) + }); } } return result; @@ -211,57 +207,57 @@ function parseUsersWin(lines) { function users(callback) { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { process.nextTick(() => { let result = []; // linux if (_linux) { - exec("who --ips; echo '---'; w | tail -n +2", function (error, stdout) { + exec('who --ips; echo "---"; w | tail -n +2', function (error, stdout) { if (!error) { // lines / split let lines = stdout.toString().split('\n'); result = parseUsersLinux(lines); if (result.length === 0) { - exec("who; echo '---'; w | tail -n +2", function (error, stdout) { + exec('who; echo "---"; w | tail -n +2', function (error, stdout) { if (!error) { // lines / split lines = stdout.toString().split('\n'); result = parseUsersLinux(lines); } - 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); } }); } if (_darwin) { - exec("who; echo '---'; w -ih", function (error, stdout) { + exec('who; echo "---"; w -ih', function (error, stdout) { if (!error) { // lines / split let lines = stdout.toString().split('\n'); result = parseUsersDarwin(lines); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } if (_windows) { - exec("query user", function (error, stdout) { + exec('query user', function (error, stdout) { if (stdout) { // lines / split let lines = stdout.toString().split('\r\n'); result = parseUsersWin(lines); } - if (callback) { callback(result) } + if (callback) { callback(result); } resolve(result); }); } diff --git a/lib/util.js b/lib/util.js index 3d32b61..336fd18 100644 --- a/lib/util.js +++ b/lib/util.js @@ -25,7 +25,7 @@ function unique(obj){ let stringify={}; for(let i=0;i