node.js – Limpar document write

Question:

I'm trying to collect the time through a server where I run the following app, but 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);

Answer:

What you specifically want to do is not possible. However, there are simple ways to solve this, even using just HTTP, instead of something like WebSockets or a library like 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, every second) it would send a response right away. Otherwise, it waits until the event happens, with the connection open (and the HTTP request pending) and then terminates the request. This requires the client (in your case the browser) to be in a loop making requests and handling the responses.

In your case, I would say the easiest thing would be to use the HTTP event-stream API. Most browsers today support this API, and you can include a script on your page to take care of browsers that don't. The idea is: 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>
Scroll to Top