How can I test if a Nodejs Response is still alive

Asked

Viewed 196 times

2

I have a Response from Nodejs(Express), how can I test if he is still alive ?

let responses = []

app.get('/', async function (req, res) {
  responses.push(res)
});

setInterval(() => {
    responses.forEach(res => {
       if('Aqui eu quero testar se a conexão ainda está viva'){
           res.write('Cadeia de bytes aqui')
       }
    })
}, 100)

In those write() i send Chunks from Audios, to test this I pass the url of the stream through VLC, and when I close VLC, I need to remove it from the list.

2 answers

3

According to the documentation of Express 4.x res.end() derives directly from response.end() of the Node core at http.ServerResponse

You can check the property response.finished that returns a Boolean "true" case response.end() is called.

I didn’t try to play your bad code a possible snippet would be something like:

while(true){
    responses.forEach(res => {
       if ( !res.finished ) {
           res.write('Cadeia de bytes aqui')
       }
    })
}

You would check if the answer "not yet finished" ie, the Boolean would still be "false" (false case ... write|use)

  • Acredtio que while (true) would stop the server from working. But anyway, res.finished really is a valid option, and I think req.complete too.

  • @Juliocesarhintzedossantos, I hope that while be just example. I don’t know where you found your reference (req.complete), would be of http.Incomingmessage and your messages ... if this is the case I think it does not serve the question because it only deals with the answers http.ServerResponse

  • I think you’re right. Maybe my comment is not pertinent (and not recommended in this case) to follow, as I did not take req.complete from any documentation, but from a test I did on my computer (after the request is answered, the object gains a property called "complete" with the value true).

  • @Lauromoraes I tested with the res.finished and it didn’t work, it can’t identify that the connection was terminated.

3

Lauro’s answer is correct, but his code will not work precisely by while (true).

To create an asynchronous loop, you can use recursion with setTimeout:

let app = require('express')();
let responses = []

app.get('/', (req, res) => {
    // o res.count que eu criei serve apenas para finalizar
    // o chamado depois de 5 iterações
    // dessa forma da pra testar pelo navegador, que só mostra
    // a resposta quando o pedido for finalizado
    res.count = 0;
    responses.push(res)
});

app.listen(2000);

// função recursiva
function responder() {

    // 'programa' uma função para ser executada daqui a 1000 ms
    setTimeout(() => {
        responses.filter(res => !res.finished).forEach(res => {
            res.count++;
            res.write('Cadeia de bytes aqui');

            // a partir de agora o res.finished será true
            if (res.count === 5) res.end();
        });

        // quando finalizar a função, chama responder novamente
        responder();
    }, 1000);

}

// inicializa o loop
responder();

Remember that javascript runs on only one core. Asynchronous functions do not run on different cores, but on the main core as well as the rest of your code. The difference is that asynchronous functions are executed after all their synchronous code is executed.

Hence the while (true) prevents any other asynchronous code from being executed: it is synchronous and infinite.

  • The while, was just an example, actually a use a setInterval, but even with the set interval it didn’t work. What I did was the following, I opened the VLC, passed my route http://localhost:8080/, it plays normally, but when I pause or close the VLC it continues with the finishedas false.

  • Would you like to do like a remote control, then? I don’t think I can help you in this case. But update your question and put this information.

Browser other questions tagged

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