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

How do I get the server uptime in Node.js?

本文关键字:服务器 运行时间 Node js      更新时间:2024-04-22

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

if(commandCheck("/uptime")){
  Give server 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));

以秒为单位获取进程的正常运行时间

    console.log(process.uptime())

以秒为单位获得操作系统正常运行时间

    console.log(require('os').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);
}

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

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

如果你想以不同的方式格式化该值或将其传递到其他地方,那么这样做应该很简单

编辑:正常运行时间的定义似乎有点不清楚。这个解决方案会告诉用户设备通电的时间,这可能是你想要的,也可能不是。

我不确定你说的是HTTP服务器、实际机器(或VPS)还是Node应用程序。以下是Node中http服务器的示例。

通过在listen回调中获取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();
});

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

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