diff --git a/CHANGELOG.md b/CHANGELOG.md index 808bf36..bb29bcc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -100,6 +100,7 @@ Other changes | Version | Date | Comment | | -------------- | -------------- | -------- | +| 3.48.2 | 2018-11-18 | `dockerContainerStats()` fixed issue `cpu_percent`, win exec | | 3.48.1 | 2018-11-17 | `docker...()` fixed issue parsing docker socket JSON | | 3.48.0 | 2018-11-17 | `diskLayout()` better interface detection (WIN), `osInfo()` added build, serial | | 3.47.0 | 2018-11-06 | `versions()` added docker, postfix | diff --git a/lib/battery.js b/lib/battery.js index e11c2e2..2af4c68 100644 --- a/lib/battery.js +++ b/lib/battery.js @@ -25,10 +25,6 @@ const _freebsd = (_platform === 'freebsd'); const _openbsd = (_platform === 'openbsd'); const _sunos = (_platform === 'sunos'); -const opts = { - windowsHide: true -}; - module.exports = function (callback) { return new Promise((resolve) => { @@ -162,7 +158,7 @@ module.exports = function (callback) { } if (_windows) { try { - exec(util.getWmic() + ' Path Win32_Battery Get BatteryStatus, DesignCapacity, EstimatedChargeRemaining /value', opts, function (error, stdout) { + exec(util.getWmic() + ' Path Win32_Battery Get BatteryStatus, DesignCapacity, EstimatedChargeRemaining /value', util.execOptsWin, function (error, stdout) { if (stdout) { let lines = stdout.split('\r\n'); let status = util.getValue(lines, 'BatteryStatus', '=').trim(); diff --git a/lib/cpu.js b/lib/cpu.js index d0b0558..7506533 100644 --- a/lib/cpu.js +++ b/lib/cpu.js @@ -26,10 +26,6 @@ const _freebsd = (_platform === 'freebsd'); const _openbsd = (_platform === 'openbsd'); const _sunos = (_platform === 'sunos'); -const opts = { - windowsHide: true -}; - let _cpu_speed = '0.00'; let _current_cpu = { user: 0, @@ -307,7 +303,7 @@ function getCpu() { } if (_windows) { try { - exec(util.getWmic() + ' cpu get name, description, revision, l2cachesize, l3cachesize, manufacturer, currentclockspeed, maxclockspeed /value', opts, function (error, stdout) { + exec(util.getWmic() + ' cpu get name, description, revision, l2cachesize, l3cachesize, manufacturer, currentclockspeed, maxclockspeed /value', util.execOptsWin, function (error, stdout) { if (!error) { let lines = stdout.split('\r\n'); let name = util.getValue(lines, 'name', '=') || ''; @@ -556,7 +552,7 @@ function cpuTemperature(callback) { } if (_windows) { try { - exec(util.getWmic() + ' /namespace:\\\\root\\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature', opts, function (error, stdout) { + exec(util.getWmic() + ' /namespace:\\\\root\\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature', util.execOptsWin, function (error, stdout) { if (!error) { let sum = 0; let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0); @@ -594,7 +590,7 @@ function cpuFlags(callback) { let result = ''; if (_windows) { try { - exec('reg query "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0" /v FeatureSet', opts, function (error, stdout) { + exec('reg query "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0" /v FeatureSet', util.execOptsWin, function (error, stdout) { if (!error) { let flag_hex = stdout.split('0x').pop().trim(); let flag_bin_unpadded = parseInt(flag_hex, 16).toString(2); @@ -784,7 +780,7 @@ function cpuCache(callback) { } if (_windows) { try { - exec(util.getWmic() + ' cpu get l2cachesize, l3cachesize /value', opts, function (error, stdout) { + exec(util.getWmic() + ' cpu get l2cachesize, l3cachesize /value', util.execOptsWin, function (error, stdout) { if (!error) { let lines = stdout.split('\r\n'); result.l1d = 0; diff --git a/lib/docker.js b/lib/docker.js index b6a61ae..56a00cd 100644 --- a/lib/docker.js +++ b/lib/docker.js @@ -120,17 +120,32 @@ function docker_calcCPUPercent(cpu_stats, precpu_stats) { * @property {Array} cpu_usage.percpu_usage */ - let cpuPercent = 0.0; - // calculate the change for the cpu usage of the container in between readings - let cpuDelta = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage; - // calculate the change for the entire system between readings - let systemDelta = cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage; + if (!_windows) { + let cpuPercent = 0.0; + // calculate the change for the cpu usage of the container in between readings + let cpuDelta = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage; + // calculate the change for the entire system between readings + let systemDelta = cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage; - if (systemDelta > 0.0 && cpuDelta > 0.0) { - cpuPercent = (cpuDelta / systemDelta) * cpu_stats.cpu_usage.percpu_usage.length * 100.0; + if (systemDelta > 0.0 && cpuDelta > 0.0) { + // calculate the change for the cpu usage of the container in between readings + cpuPercent = (cpuDelta / systemDelta) * cpu_stats.cpu_usage.percpu_usage.length * 100.0; + } + + return cpuPercent; + } else { + let nanoSecNow = util.nanoSeconds(); + let cpuPercent = 0.0; + if (_docker_last_read > 0) { + let possIntervals = (nanoSecNow - _docker_last_read) // / 100 * os.cpus().length; + let intervalsUsed = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage; + if (possIntervals > 0) { + cpuPercent = 100.0 * intervalsUsed / possIntervals; + } + } + _docker_last_read = nanoSecNow; + return cpuPercent; } - - return cpuPercent; } function docker_calcNetworkIO(networks) { diff --git a/lib/filesystem.js b/lib/filesystem.js index b24304e..df2fc54 100644 --- a/lib/filesystem.js +++ b/lib/filesystem.js @@ -27,10 +27,6 @@ const _sunos = (_platform === 'sunos'); const NOT_SUPPORTED = 'not supported'; -const opts = { - windowsHide: true -}; - let _fs_speed = {}; let _disk_io = {}; @@ -79,7 +75,7 @@ function fsSize(callback) { } if (_windows) { try { - exec(util.getWmic() + ' logicaldisk get Caption,FileSystem,FreeSpace,Size', opts, function (error, stdout) { + exec(util.getWmic() + ' logicaldisk get Caption,FileSystem,FreeSpace,Size', util.execOptsWin, function (error, stdout) { let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0); lines.forEach(function (line) { if (line !== '') { @@ -264,7 +260,7 @@ function blockDevices(callback) { if (_windows) { let drivetypes = ['Unknown', 'NoRoot', 'Removable', 'Local', 'Network', 'CD/DVD', 'RAM']; try { - exec(util.getWmic() + ' logicaldisk get Caption,Description,DeviceID,DriveType,FileSystem,FreeSpace,Name,Size,VolumeName,VolumeSerialNumber /value', opts, function (error, stdout) { + exec(util.getWmic() + ' logicaldisk get Caption,Description,DeviceID,DriveType,FileSystem,FreeSpace,Name,Size,VolumeName,VolumeSerialNumber /value', util.execOptsWin, function (error, stdout) { if (!error) { let devices = stdout.toString().split(/\n\s*\n/); devices.forEach(function (device) { diff --git a/lib/graphics.js b/lib/graphics.js index 8e39cee..499173c 100644 --- a/lib/graphics.js +++ b/lib/graphics.js @@ -24,10 +24,6 @@ const _freebsd = (_platform === 'freebsd'); const _openbsd = (_platform === 'openbsd'); const _sunos = (_platform === 'sunos'); -const opts = { - windowsHide: true -}; - let _resolutionx = 0; let _resolutiony = 0; let _pixeldepth = 0; @@ -154,7 +150,7 @@ function graphics(callback) { } else if (parts[1].toLowerCase().indexOf(' inc.') >= 0) { 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]; + currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']') + 1, 200).trim().split('(')[0]; } else { currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(' inc.') + 5).trim(); currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(' inc.') + 5, 200).trim().split('(')[0]; @@ -339,11 +335,11 @@ function graphics(callback) { if (_windows) { // https://blogs.technet.microsoft.com/heyscriptingguy/2013/10/03/use-powershell-to-discover-multi-monitor-information/ try { - exec(util.getWmic() + ' path win32_VideoController get AdapterCompatibility, AdapterDACType, name, PNPDeviceID, CurrentVerticalResolution, CurrentHorizontalResolution, CurrentNumberOfColors, AdapterRAM, CurrentBitsPerPixel, CurrentRefreshRate, MinRefreshRate, MaxRefreshRate, VideoMemoryType /value', opts, function (error, stdout) { + exec(util.getWmic() + ' path win32_VideoController get AdapterCompatibility, AdapterDACType, name, PNPDeviceID, CurrentVerticalResolution, CurrentHorizontalResolution, CurrentNumberOfColors, AdapterRAM, CurrentBitsPerPixel, CurrentRefreshRate, MinRefreshRate, MaxRefreshRate, VideoMemoryType /value', util.execOptsWin, function (error, stdout) { if (!error) { let csections = stdout.split(/\n\s*\n/); result.controllers = parseLinesWindowsControllers(csections); - exec(util.getWmic() + ' path win32_desktopmonitor get Caption, MonitorManufacturer, MonitorType, ScreenWidth, ScreenHeight /value', opts, function (error, stdout) { + exec(util.getWmic() + ' path win32_desktopmonitor get Caption, MonitorManufacturer, MonitorType, ScreenWidth, ScreenHeight /value', util.execOptsWin, function (error, stdout) { let dsections = stdout.split(/\n\s*\n/); if (!error) { result.displays = parseLinesWindowsDisplays(dsections); @@ -365,7 +361,7 @@ function graphics(callback) { resolve(result); }); } - }); + }); } catch (e) { if (callback) { callback(result); } resolve(result); diff --git a/lib/index.js b/lib/index.js index 981c859..c6dc2d2 100644 --- a/lib/index.js +++ b/lib/index.js @@ -15,69 +15,6 @@ // ---------------------------------------------------------------------------------- // License: MIT // ================================================================================== -// -// Sections -// -------------------------------- -// 1. General -// 2. System (HW) -// 3. OS - Operating System -// 4. CPU -// 5. Memory -// 6. Battery -// 7. Graphics -// 8. File System -// 9. Network -// 10. Processes -// 11. Users/Sessions -// 12. Internet -// 13. Docker -// 14. GetAll - get all data -// -// ================================================================================== -// -// Installation -// -------------------------------- -// -// # npm install systeminformation --save -// -// Since version 2.0 systeminformation has no more dependencies. -// -// ================================================================================== -// -// Usage -// -------------------------------- -// All functions (except `version` and `time`) are asynchronous functions. Here a small example how to use them: -// -// var si = require('systeminformation'); -// -// // callback style -// si.cpu(function(data) { -// console.log('CPU-Information:'); -// console.log(data); -// }) -// -// // promises style -// si.cpu() -// .then(data => console.log(data)) -// .catch(error => console.error(error)); -// -// ================================================================================== -// -// Comments -// -------------------------------- -// -// This library is still work in progress. Version 3 comes with further improvements. First it -// requires now node.js version 4.0 and above. Another big change is, that all functions now -// return promises. You can use them like before with callbacks OR with promises -// (see example in this documentation). I am sure, there is for sure room for improvement. -// I was only able to test it on several Debian, Raspbian, Ubuntu distributions as well as -// OS X (Mavericks, Yosemite, El Captain) and some Windows machines. -// Since version 2 nearly all functionality is available for OS X/Darwin platforms. -// In Version 3 I started to add (limited!) windows support. -// -// Comments, suggestions & reports are very welcome! -// -// ================================================================================== // ---------------------------------------------------------------------------------- // Dependencies @@ -105,7 +42,15 @@ const _openbsd = (_platform === 'openbsd'); const _sunos = (_platform === 'sunos'); // ---------------------------------------------------------------------------------- -// 1. General +// init +// ---------------------------------------------------------------------------------- + +if (_windows) { + util.getWinCodepage(); +} + +// ---------------------------------------------------------------------------------- +// General // ---------------------------------------------------------------------------------- function version() { @@ -113,7 +58,7 @@ function version() { } // ---------------------------------------------------------------------------------- -// 14. get all +// Get static and dynamic data (all) // ---------------------------------------------------------------------------------- // -------------------------- diff --git a/lib/internet.js b/lib/internet.js index 8ec6f42..41e4d97 100644 --- a/lib/internet.js +++ b/lib/internet.js @@ -24,10 +24,6 @@ const _freebsd = (_platform === 'freebsd'); const _openbsd = (_platform === 'openbsd'); const _sunos = (_platform === 'sunos'); -const opts = { - windowsHide: true -}; - // -------------------------- // check if external site is available @@ -141,7 +137,7 @@ function inetLatency(host, callback) { }); } if (_sunos) { - exec('ping -s -a ' + host + ' 56 2 | grep avg', {timeout: 3000}, function (error, stdout) { + exec('ping -s -a ' + host + ' 56 2 | grep avg', { timeout: 3000 }, function (error, stdout) { let result = -1; if (!error) { const line = stdout.toString().split('='); @@ -159,7 +155,7 @@ function inetLatency(host, callback) { if (_windows) { let result = -1; try { - exec('ping ' + host + ' -n 1', opts, function (error, stdout) { + exec('ping ' + host + ' -n 1', util.execOptsWin, function (error, stdout) { if (!error) { let lines = stdout.toString().split('\r\n'); lines.shift(); @@ -174,7 +170,7 @@ function inetLatency(host, callback) { } if (callback) { callback(result); } resolve(result); - }); + }); } catch (e) { if (callback) { callback(result); } resolve(result); diff --git a/lib/memory.js b/lib/memory.js index af7303e..70c8c80 100644 --- a/lib/memory.js +++ b/lib/memory.js @@ -25,10 +25,6 @@ const _freebsd = (_platform === 'freebsd'); const _openbsd = (_platform === 'openbsd'); const _sunos = (_platform === 'sunos'); -const opts = { - windowsHide: true -}; - const OSX_RAM_manufacturers = { '0x014F': 'Transcend Information', '0x2C00': 'Micron Technology Inc.', @@ -200,7 +196,7 @@ function mem(callback) { let swaptotal = 0; let swapused = 0; try { - exec(util.getWmic() + ' pagefile get AllocatedBaseSize, CurrentUsage', opts, function (error, stdout) { + exec(util.getWmic() + ' pagefile get AllocatedBaseSize, CurrentUsage', util.execOptsWin, function (error, stdout) { if (!error) { let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0); lines.forEach(function (line) { @@ -338,7 +334,7 @@ function memLayout(callback) { 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('|'); try { - exec(util.getWmic() + ' memorychip get BankLabel, Capacity, ConfiguredClockSpeed, ConfiguredVoltage, MaxVoltage, MinVoltage, DataWidth, FormFactor, Manufacturer, MemoryType, PartNumber, SerialNumber, Speed, Tag /value', opts, function (error, stdout) { + exec(util.getWmic() + ' memorychip get BankLabel, Capacity, ConfiguredClockSpeed, ConfiguredVoltage, MaxVoltage, MinVoltage, DataWidth, FormFactor, Manufacturer, MemoryType, PartNumber, SerialNumber, Speed, Tag /value', util.execOptsWin, function (error, stdout) { if (!error) { let devices = stdout.toString().split('BankL'); devices.shift(); diff --git a/lib/network.js b/lib/network.js index 13ff987..395a376 100644 --- a/lib/network.js +++ b/lib/network.js @@ -27,11 +27,6 @@ const _freebsd = (_platform === 'freebsd'); const _openbsd = (_platform === 'openbsd'); const _sunos = (_platform === 'sunos'); -const opts = { - windowsHide: true, - maxBuffer: 1024 * 2000 -}; - let _network = {}; let _default_iface; let _mac = {}; @@ -368,14 +363,14 @@ function networkStats(iface, callback) { let nics = []; cmd = util.getWmic() + ' nic get MACAddress, name, NetEnabled /value'; try { - exec(cmd, opts, function (error, stdout) { + exec(cmd, util.execOptsWin, function (error, stdout) { if (!error) { const nsections = stdout.split(/\n\s*\n/); nics = parseLinesWindowsNics(nsections); // Performance Data cmd = util.getWmic() + ' path Win32_PerfRawData_Tcpip_NetworkInterface Get name,BytesReceivedPersec,BytesSentPersec,BytesTotalPersec /value'; - exec(cmd, opts, function (error, stdout) { + exec(cmd, util.execOptsWin, function (error, stdout) { if (!error) { const psections = stdout.split(/\n\s*\n/); perfData = parseLinesWindowsPerfData(psections); @@ -589,7 +584,7 @@ function networkConnections(callback) { if (_windows) { let cmd = 'netstat -na'; try { - exec(cmd, opts, function (error, stdout) { + exec(cmd, util.execOptsWin, function (error, stdout) { if (!error) { let lines = stdout.toString().split('\r\n'); diff --git a/lib/osinfo.js b/lib/osinfo.js index b8bef24..900518c 100644 --- a/lib/osinfo.js +++ b/lib/osinfo.js @@ -26,10 +26,6 @@ const _freebsd = (_platform === 'freebsd'); const _openbsd = (_platform === 'openbsd'); const _sunos = (_platform === 'sunos'); -const opts = { - windowsHide: true -}; - const NOT_SUPPORTED = 'not supported'; // -------------------------- @@ -253,7 +249,7 @@ function osInfo(callback) { result.logofile = getLogoFile(); result.release = result.kernel; try { - exec(util.getWmic() + ' os get /value', opts, function (error, stdout) { + util.execWin(util.getWmic() + ' os get /value', util.execOptsWin, function (error, stdout) { let lines = stdout.toString().split('\r\n'); result.distro = util.getValue(lines, 'Caption', '=').trim(); result.serial = util.getValue(lines, 'SerialNumber', '=').trim(); diff --git a/lib/processes.js b/lib/processes.js index ed7df78..8997fc6 100644 --- a/lib/processes.js +++ b/lib/processes.js @@ -149,7 +149,7 @@ function services(srv, callback) { } if (_windows) { try { - exec(util.getWmic() + ' service get /value', { maxBuffer: 1024 * 1000, windowsHide: true }, function (error, stdout) { + exec(util.getWmic() + ' service get /value', util.execOptsWin, function (error, stdout) { if (!error) { let serviceSections = stdout.split(/\n\s*\n/); for (let i = 0; i < serviceSections.length; i++) { @@ -615,7 +615,7 @@ function processes(callback) { } if (_windows) { try { - exec(util.getWmic() + ' process get /value', { maxBuffer: 1024 * 2000, windowsHide: true }, function (error, stdout) { + exec(util.getWmic() + ' process get /value', util.execOptsWin, function (error, stdout) { if (!error) { let processSections = stdout.split(/\n\s*\n/); let procs = []; diff --git a/lib/system.js b/lib/system.js index 4e1c72c..ea103bc 100644 --- a/lib/system.js +++ b/lib/system.js @@ -25,10 +25,6 @@ const _freebsd = (_platform === 'freebsd'); const _openbsd = (_platform === 'openbsd'); const _sunos = (_platform === 'sunos'); -const opts = { - windowsHide: true -}; - function system(callback) { return new Promise((resolve) => { @@ -189,7 +185,7 @@ function system(callback) { } if (_windows) { try { - exec(util.getWmic() + ' csproduct get /value', opts, function (error, stdout) { + exec(util.getWmic() + ' csproduct get /value', util.execOptsWin, 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+/); let lines = stdout.split('\r\n'); @@ -198,7 +194,7 @@ function system(callback) { result.version = util.getValue(lines, 'version', '='); result.serial = util.getValue(lines, 'identifyingnumber', '='); result.uuid = util.getValue(lines, 'uuid', '='); - exec(util.getWmic() + ' /namespace:\\\\root\\wmi path MS_SystemInformation get /value', opts, function (error, stdout) { + exec(util.getWmic() + ' /namespace:\\\\root\\wmi path MS_SystemInformation get /value', util.execOptsWin, function (error, stdout) { if (!error) { let lines = stdout.split('\r\n'); result.sku = util.getValue(lines, 'systemsku', '='); @@ -267,7 +263,7 @@ function bios(callback) { if (_windows) { // TODO: check BIOS windows try { - exec(util.getWmic() + ' bios get /value', opts, function (error, stdout) { + exec(util.getWmic() + ' bios get /value', util.execOptsWin, function (error, stdout) { if (!error) { let lines = stdout.toString().split('\r\n'); const description = util.getValue(lines, 'description', '='); @@ -361,7 +357,7 @@ function baseboard(callback) { } if (_windows) { try { - exec(util.getWmic() + ' baseboard get /value', opts, function (error, stdout) { + exec(util.getWmic() + ' baseboard get /value', util.execOptsWin, function (error, stdout) { if (!error) { let lines = stdout.toString().split('\r\n'); diff --git a/lib/users.js b/lib/users.js index 55e31c4..7302c39 100644 --- a/lib/users.js +++ b/lib/users.js @@ -24,10 +24,6 @@ const _freebsd = (_platform === 'freebsd'); const _openbsd = (_platform === 'openbsd'); const _sunos = (_platform === 'sunos'); -const opts = { - windowsHide: true -}; - // -------------------------- // array of users online = sessions @@ -150,10 +146,10 @@ function parseUsersWin(lines) { const headerDelimiter = []; if (header) { const start = (header[0] === ' ') ? 1 : 0; - headerDelimiter.push(start-1); + headerDelimiter.push(start - 1); let nextSpace = 0; - for (let i = start+1; i < header.length; i++) { - if (header[i] === ' ' && header[i-1] === ' ') { + for (let i = start + 1; i < header.length; i++) { + if (header[i] === ' ' && header[i - 1] === ' ') { nextSpace = i; } else { if (nextSpace) { @@ -165,9 +161,9 @@ function parseUsersWin(lines) { } for (let i = 1; i < lines.length; i++) { if (lines[i].trim()) { - const user = lines[i].substring(headerDelimiter[0]+1, headerDelimiter[1]).trim() || ''; - const tty = lines[i].substring(headerDelimiter[1]+1, headerDelimiter[2] - 2).trim() || ''; - const dateTime = util.parseDateTime(lines[i].substring(headerDelimiter[5]+1, 2000).trim()) || ''; + const user = lines[i].substring(headerDelimiter[0] + 1, headerDelimiter[1]).trim() || ''; + const tty = lines[i].substring(headerDelimiter[1] + 1, headerDelimiter[2] - 2).trim() || ''; + const dateTime = util.parseDateTime(lines[i].substring(headerDelimiter[5] + 1, 2000).trim()) || ''; result.push({ user: user, tty: tty, @@ -250,7 +246,7 @@ function users(callback) { } if (_windows) { try { - exec('query user', opts, function (error, stdout) { + exec('query user', util.execOptsWin, function (error, stdout) { if (stdout) { // lines / split let lines = stdout.toString().split('\r\n'); @@ -258,10 +254,10 @@ function users(callback) { } if (callback) { callback(result); } resolve(result); - }); + }); } catch (e) { if (callback) { callback(result); } - resolve(result); + resolve(result); } } diff --git a/lib/util.js b/lib/util.js index 987a524..06c2d20 100644 --- a/lib/util.js +++ b/lib/util.js @@ -15,6 +15,21 @@ const os = require('os'); const fs = require('fs'); const spawn = require('child_process').spawn; +const exec = require('child_process').exec; +const execSync = require('child_process').execSync; + +let _platform = process.platform; +const _windows = (_platform === 'win32'); + +let _cores = 0; +let wmic = ''; +let codepageWin = ''; + +const execOptsWin = { + windowsHide: true, + maxBuffer: 1024 * 2000, + encoding: 'UTF-8' +}; let _cores = 0; let wmic = ''; @@ -170,8 +185,46 @@ function powerShell(cmd) { }); } +function getWinCodepage() { + if (_windows) { + if (!codepageWin) { + try { + const stdout = execSync('chcp'); + const lines = stdout.toString().split('\r\n'); + const parts = lines[0].split(':'); + codepageWin = parts.length > 1 ? parts[1].replace('.', '') : ''; + } catch (err) { + codepageWin = '437'; + } + } + return codepageWin; + } +} + +function execWin(cmd, opts, callback) { + if (!callback) { + callback = opts; + opts = execOptsWin; + } + newCmd = 'chcp 65001 > nul && cmd /C ' + cmd + ' && chcp ' + codepageWin + ' > nul'; + exec(newCmd, util.execOptsWin, function (error, stdout) { + callback(error, stdout) + }) +} + +function nanoSeconds() { + const time = process.hrtime(); + if (!Array.isArray(time) || time.length !== 2) { + return 0; + } + return +time[0] * 1e9 + +time[1]; +} + function noop() { } +exports.execOptsWin = execOptsWin; +exports.getWinCodepage = getWinCodepage; +exports.execWin = execWin; exports.isFunction = isFunction; exports.unique = unique; exports.sortByKey = sortByKey; @@ -182,4 +235,5 @@ exports.parseDateTime = parseDateTime; exports.findObjectByKey = findObjectByKey; exports.getWmic = getWmic; exports.powerShell = powerShell; +exports.nanoSeconds = nanoSeconds; exports.noop = noop;