如何在Node.js中获得服务器正常运行时间?

如何在Node.js中获得服务器正常运行时间,以便可以通过如下命令输出它;

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

现在我不知道如何计算服务器启动的正常运行时间。

你可以做什么来获得正常的时间格式是;

 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); } 

你可以使用process.uptime() 。 只需调用它即可获取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)); 

假设这是一个* nix服务器,可以使用uptime shell命令使用child_process

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

如果你想以不同的方式格式化这个值,或者把它传递到别的地方,那么这么做应该是微不足道的。

编辑:正常运行时间的定义似乎有点不清楚。 该解决scheme将告诉用户该设备已启动多久,这可能是也可能不是你所追求的。

我不确定你是在谈论一个HTTP服务器,一台真正的机器(或VPS),或者只是一个Node应用程序。 下面是Node中的一个http服务器的例子。

通过在listencallback中获取Date.now()存储服务器启动的时间。 然后,您可以通过在另一个时间点从Date.now()中减去此值来计算正常运行时间。

 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(); }); 

在几秒钟内获得进程的正常运行时间

  console.log(process.uptime()) 

在几秒钟内让操作系统正常运行

  console.log(require('os').uptime()) 

要同步获得ms的unix正常运行时间:

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