LachlanDev
LachlanDev

Reputation: 355

Socket.io live uptime of NodeJS Application?

I have a Node.JS express server running a website, I would like to add a live uptime of the website to the front end for users. Currently I am passing the data to the website when the user requests the page. I would like have the uptime show live (update on the page live) I have tried to do this using socket.io with this code.

io.sockets.on('connection', function(sockets){
  var uptime = process.uptime();
  const date = new Date(uptime*1000);
  const days = date.getUTCDate() - 1,
        hours = date.getUTCHours(),
        minutes = date.getUTCMinutes(),
        seconds = date.getUTCSeconds(),
        milliseconds = date.getUTCMilliseconds();
  let segments = [];
  if (days > 0) segments.push(days + ' day' + ((days == 1) ? '' : 's'));
  if (hours > 0) segments.push(hours + ' hour' + ((hours == 1) ? '' : 's'));
  if (minutes > 0) segments.push(minutes + ' minute' + ((minutes == 1) ? '' : 's'));
  if (seconds > 0) segments.push(seconds + ' second' + ((seconds == 1) ? '' : 's'));
  const dateString = segments.join(', ');

  io.sockets.emit('count', {count:dateString})
})

It seems to work for 2 seconds (updating twice) then no more data is sent to the front end. Any ideas on how I can send process.uptime(); to the front end? Cheers

EDIT: I needed to add a setInterval(function() and also update the dateString from a const here is the server updated code,

io.sockets.on('connection', function(sockets){
  setInterval(function(){ 
    var uptime = process.uptime();
    const date = new Date(uptime*1000);
    const days = date.getUTCDate() - 1,
      hours = date.getUTCHours(),
      minutes = date.getUTCMinutes(),
      seconds = date.getUTCSeconds();
    let segments = [];

    if (days > 0) segments.push(days + ' day' + ((days == 1) ? '' : 's'));
    if (hours > 0) segments.push(hours + ' hour' + ((hours == 1) ? '' : 's'));
    if (minutes > 0) segments.push(minutes + ' minute' + ((minutes == 1) ? '' : 's'));
    if (seconds > 0) segments.push(seconds + ' second' + ((seconds == 1) ? '' : 's'));
    dateString = segments.join(', ');
    
    sockets.emit('count',{count:dateString}); }, 1000);
})

And client code

    <script>
      var socket = io();
      socket.on('count', function(data){
        $('#count').html(data.count);
      });
    </script>

Result:

enter image description here

Upvotes: 0

Views: 251

Answers (1)

Oz Heymann
Oz Heymann

Reputation: 644

It seems that you only emit the uptime to the connected clients when a client connects. Every time a client connects, the function under the 'connection' event is being run.

If you want it to run automatically (let's say, every second) you could set an interval that emits the uptime state every second.

Upvotes: 1

Related Questions