Clear document write

3

I am trying to collect the time through a server where I squeeze the following app, so the problem is that when I do the res.write it repeats, is there any way to clear the screen to generate a new write?

http = require('http');
http.createServer(function (req, res, err) {

    if(err){ throw err; }

    res.writeHead(200, {'Content-Type': 'text/plain'});
    var time = new Date();
    setInterval(function(){

        time = new Date();
        res.write(
            time.getHours()
            + ':' +
            time.getMinutes()
            + ':' +
            time.getSeconds() 
        );

       // res.end();

    },1000);
}).listen(8090);
    
asked by anonymous 26.02.2015 / 19:55

1 answer

1

What you specifically want to do is not possible. However, there are simple ways to resolve this, even using HTTP only, rather than something like WebSockets or a library such as Socket.IO.

A common technique is called Long Pooling . The idea is that you open an HTTP request on the client side and wait for a response. If the server has an event to send (in your case the time, one in a second) it would send a response on time. Otherwise, it waits until the event occurs, with the connection open (and the HTTP request pending), and then terminates the request. This requires that the client (in your case the browser) stay in a loop making requests and handling the responses.

In your case, I would say the easiest would be to use the event-stream API for HTTP. Most browsers today support this API, and you can include a script on your page to take care of browsers that do not support it. The idea is this: every time the server wants to send data to the client, it writes data: followed by the data it wants to send and two line breaks ( \n\n ) k. You also need to change the Content-Type to text/event-stream . Your server would look like this to support this:

'use strict';
var http = require('http');

http.createServer(function(req, res, err) {
  if(err) throw err;

  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Access-Control-Allow-Origin': '*',
  });

  setInterval(function() {
    var now = new Date();
    console.log('sending data ' + now);
    res.write(
      'data:' +
      now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '\n\n'
    );
  }, 1000);
}).listen(3000);

On the client side, you use the browser API:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8"/>
    <title>Document</title>
  </head>
  <body>
    <p id="current-time"></p>
    <script type="text/javascript">
var currentTimeEl = document.getElementById('current-time');
var stream = new EventSource('http://127.0.0.1:3000');

stream.addEventListener('open', function(e) {
  console.log(e);
});

stream.addEventListener('message', function(e) {
  console.log(e);
  currentTimeEl.innerHTML = e.data;
});
    </script>
  </body>
</html>
    
27.02.2015 / 17:11