How Do I Get The Server Uptime In Node.js?
Solution 1:
You can use process.uptime()
. Just call that to get the number of seconds since node
was started.
function format(seconds){
function pad(s){
return (s < 10 ? '0' : '') + s;
}
var hours = Math.floor(seconds / (60*60));
var minutes = Math.floor(seconds % (60*60) / 60);
var seconds = Math.floor(seconds % 60);
return pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
}
var uptime = process.uptime();
console.log(format(uptime));
Solution 2:
To get process's uptime in seconds
console.log(process.uptime())
To get OS uptime in seconds
console.log(require('os').uptime())
Solution 3:
What you can do to get normal time format is;
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+':'+minutes+':'+seconds;
return time;
}
if(commandCheck("/uptime")){
var time = process.uptime();
var uptime = (time + "").toHHMMSS();
console.log(uptime);
}
Solution 4:
Assuming this is a *nix server, you can use the uptime
shell command using child_process
:
var child = require('child_process');
child.exec('uptime', function (error, stdout, stderr) {
console.log(stdout);
});
If you want to format that value differently or pass it through somewhere else, it should be trivial to do so.
EDIT: The definition of uptime seems a little unclear. This solution will tell the user how long the device has been powered on for, which may or may not be what you're after.
Solution 5:
I'm not sure if you're talking about an HTTP server, an actual machine (or VPS) or just a Node app in general. Here's an example for an http
server in Node though.
Store the time when your server starts by getting Date.now()
inside the listen
callback. And then you can calculate uptime by subtracting this value from Date.now()
at another point in time.
var http = require('http');
var startTime;
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Uptime: ' + (Date.now() - startTime) + 'ms');
});
server.listen(3000, function () {
startTime = Date.now();
});
Post a Comment for "How Do I Get The Server Uptime In Node.js?"