Clear Document write

Asked

Viewed 507 times

3

I’m trying to collect the time through a server where I run the following app, only that the problem is that when I do the res.write it repeats, there is some 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);
  • It repeats itself in the same requisition? I did not understand well sorry, could explain in what moment repeats?

  • when I search localhost:8090 it appears like.. 10:00:0110:00:02 10:00:03 ... and if it repeats, I wanted it to stay static

  • It’s not because of setInterval?

  • yes more I need to upgrade to play in an iframe

  • But shouldn’t the update be done by front-end to each request? Even use Ajax preference

  • have tried res.send?

  • not pq I want the server time , this ap will serve several pages

  • @Rafaelvergopolan I will agree with Guilherme, if you have a setInval and the process is asynchronous and he will keep writing several times in Sponse until you send the answer. Why are you using setInterval?

  • I am trying to generate by the simplest way without express, the interval is to update the time in real time

  • Maybe you should use something like http.request(options, callback);, sorry if I’m talking nonsense, I’ve never used Node.js.

  • I’ll have to do it for the client.. directly from the server I don’t think

  • That’s more or less what I wanted to say. A question, why <iframe> it would not be better to ajax?

  • pq will have to be making requests to update the time

  • @Rafaelvergopolan, you can use websockets, then you will receive updates in real time, but just to update the time I think it is the famous case of "bazuca kills flies"

  • Rafael but that’s exactly what ajax does, requests to the server :)

Show 10 more comments

1 answer

1

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

A common technique is the so-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 time, one in a second) it would send a reply on time. 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 stay in a loop making requests and dealing with the answers.

In your case, I would say that the easiest would be to use the API event-stream of 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 you want to send and two line breaks (\n\n)k. It is also necessary to change the Content-Type for 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>
  • 1

    this method would match the code I showed, repeating the hours I made with socket.io ;)

  • It would look the same if you access your server page. If you open this HTML page you will get the desired effect. Similarly, if you open a Websockets server (like the socket.io without being in compatibility mode) and open a connection by telnet for it, you will see the text repeating itself every time more data arrive. So is the network.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.