How to get server uptime in Node.js?

How to get server uptime in Node.js so that I can output it with the command:

if(commandCheck("/uptime")){ Give server uptime; } 

Now I do not know how to calculate the uptime at server startup.

+5
source share
6 answers

What you can do to get a normal time format:

 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); } 
+3
source

You can use process.uptime() . Just call to get the number of seconds since starting node .

 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)); 
+9
source

Assuming this is a * nix server, you can use the uptime shell uptime using child_process :

 var child = require('child_process'); child.exec('uptime', function (error, stdout, stderr) { console.log(stdout); }); 

If you want to format this value differently or pass it through to another location, this should be trivial for this.

EDIT: Determining uptime seems a bit unclear. This decision will tell the user how long the device has been turned on, which may or may not be what you are after.

+3
source

To get uptime in seconds

  console.log(process.uptime()) 

To speed up the OS in seconds

  console.log(require('os').uptime()) 
+2
source

I'm not sure if you're talking about an HTTP server, an actual computer (or VPS), or just a Node application in general. Here is an example for the http server in Node.

Keep the time when your server starts receiving Date.now() inside the listen callback. And then you can calculate the 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(); }); 
+1
source

To synchronize unix time in ms:

 const fs= require("fs"); function getSysUptime(){ return parseFloat(fs.readFileSync("/proc/uptime", { "encoding": "utf8" }).split(" ")[0])*1000; } console.log(getSysUptime()); 
0
source

Source: https://habr.com/ru/post/1214106/


All Articles