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

Inn*_*nna 8 javascript node.js

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

if(commandCheck("/uptime")){
  Give server uptime;
}
Run Code Online (Sandbox Code Playgroud)

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

log*_*yth 16

你可以用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));
Run Code Online (Sandbox Code Playgroud)


小智 7

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

    console.log(process.uptime())
Run Code Online (Sandbox Code Playgroud)

在几秒钟内获得OS正常运行时间

    console.log(require('os').uptime())
Run Code Online (Sandbox Code Playgroud)


小智 6

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

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 底线:`process.uptime();` - 其余的是不必要的. (11认同)
  • 没有任何关于这需要增加字符串原型. (8认同)