K2xL
K2xL

Reputation: 10330

nodejs and expressjs

app.get('/', function(req, res) {
    res.set('Content-Type', 'text/html');
    res.send('Yo');
    setTimeout(function(){
        res.send("Yo");
    },1000);
});

It looks like "send" ends the request. How can I get this to write Yo on the screen and then 1 second later (sort of like long polling I guess) write the other Yo to get YoYo? Is there some other method other than send?

Upvotes: 1

Views: 321

Answers (5)

mariosk89
mariosk89

Reputation: 954

the thing with node.js is that it relies on an asynchronous "style". so if you introduce something like a "wait" function, you'll lose all the benefits of the asynchronous way of execution.

I believe you can achieve something similar to what you want by:

  1. (asynchronous way) including a function that prints the second "Yo" as a callback to the first function (or)
  2. (classic wait(synchronous) ) introduce a 'big' loop before presenting the second 'Yo'.

for example:

for(i=0; i < 100000000; i++) {
    //do something
}

Upvotes: 0

Samuel0Paul
Samuel0Paul

Reputation: 7

If you want to send the result as a single block try

app.get('/', function(req, res) {
    res.set('Content-Type', 'text/html');
    res.write('Yo');
    setTimeout(function(){
        res.end("Yo");
    },1000);
});

or something like

app.get('/', function(req, res) {
    res.set('Content-Type', 'text/html');
    var str = 'yo';
    setTimeout(function(){
        res.end(str + 'yo');
    },1000);
});

Upvotes: 0

jorg.mer
jorg.mer

Reputation: 155

Try with JQuery+JSON. send the response and then update what ever you need with JQuery and JSON.

This is a good tutorial of expressjs, including DB stuff (mongodb).

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 312115

Use res.write to generate output in pieces and then complete the response with res.end.

Upvotes: 2

Thorsten Lorenz
Thorsten Lorenz

Reputation: 11847

I don't think what you are trying to do is possible. Once you send a response, the client-server connection will be closed.

Look into sockets (particularly socket.io) in order to keep a connection open and send multiple messages on it.

Upvotes: 1

Related Questions