Created
March 6, 2017 14:15
-
-
Save servercharlie/36398a3c926f4f9cb542c1c4da2d16b5 to your computer and use it in GitHub Desktop.
SMUI - Simple Memory Usage Info
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
SMUI: | |
- Simple Memory Usage Info | |
Dependencies: | |
- pidusage (npm install pidusage --save ) | |
- eventemitter3 (npm install eventemitter3 --save) | |
Thanks: | |
- Primus & Soyuka @ GitHub | |
- Bytes Formatting @ http://stackoverflow.com/a/18650828 | |
**/ | |
const SMUI = {}; | |
SMUI.modules = {}; | |
SMUI.modules.pidusage = require('pidusage'); | |
SMUI.modules.EventEmitter = require('eventemitter3'); | |
SMUI.formatBytes = function (bytes,decimals) { | |
if(bytes == 0) return '0 Bytes'; | |
var k = 1000, | |
dm = decimals + 1 || 3, | |
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], | |
i = Math.floor(Math.log(bytes) / Math.log(k)); | |
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; | |
}; | |
SMUI.eventEmitter = new SMUI.modules.EventEmitter(); | |
SMUI.startMonitoring = function(interval){ | |
var self = this; | |
this.timer = setInterval(function(){ | |
self.modules.pidusage.stat(process.pid, function(err, stat){ | |
self.eventEmitter.emit('update', { | |
raw: stat.memory, | |
formatted: self.formatBytes(stat.memory, 1) | |
}); | |
}); | |
}, interval); | |
}; | |
SMUI.stopMonitoring = function(){ | |
clearInterval(this.timer); | |
this.modules.pidusage.unmonitor(process.pid); | |
}; | |
/** USAGE **/ | |
SMUI.startMonitoring(500); | |
SMUI.eventEmitter.on('update', function (usage) { | |
console.log(usage); | |
}); | |
setTimeout(function(){ | |
SMUI.stopMonitoring(); | |
}, 2000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment