Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs request proxy stream(mjpeg) connection never ends

(unnecessary backstory) I have a nodejs server with expressjs framework that's proxy streaming a webcam feed. The reason I need this is because the mjpg stream must come from this server due to complex CORS issues.

//proxy from webcam server to avoid CORS complaining
app.get('/stream1',function(req,res){
    var url="http://camera.nton.lviv.ua/mjpg/video.mjpg"
    request(url).pipe(res);
});

question : The issue is simple. request(url).pipe(res) never closes, because the source is mjpeg which literally never ends. I need to find a way to force close this pipe when the client(browser; the destination) is no longer available - as in, closes the window.

enter image description here

like image 608
Gyuhyeon Lee Avatar asked Sep 12 '26 19:09

Gyuhyeon Lee


2 Answers

The other answers did not work for me. This line var pipe=request(url).pipe(res); returns the pipe instead of the request object. So I needed to break the line up.

The request object is needed to abort. Calling the .end() didn't work either, but the .abort() did the trick. It took me hours to find the answer that worked for me, so I thought I would share.

   app.get('/cam/frontdoor',function(req,res){

        var request_options = {
            auth: {
                user: '',
                pass: ''},
            url: 'http:/xx.xx.xx.xx/mjpg/video.mjpg',
        };

        var req_pipe = request(request_options);
        req_pipe.pipe(res);

        req_pipe.on('error', function(e){
            console.log(e)
        });
        //client quit normally
        req.on('end', function(){
            console.log('end');
            req_pipe.abort();

        });
        //client quit unexpectedly
        req.on('close', function(){
            console.log('close');
            req_pipe.abort()

        })


    })
like image 125
twitzel Avatar answered Sep 15 '26 08:09

twitzel


I have found out a simpler way. Add a event listener for client connection closing, and force close the pipe when it happens.

app.get('/stream1',function(req,res){
    var url="http://camera.nton.lviv.ua/mjpg/video.mjpg"
    var pipe=request(url).pipe(res);
    pipe.on('error', function(){
        console.log('error handling is needed because pipe will break once pipe.end() is called')
    }
    //client quit normally
    req.on('end', function(){
        pipe.end();
    }
    //client quit unexpectedly
    req.on('close', function(){
        pipe.end();
    }
});
like image 29
Gyuhyeon Lee Avatar answered Sep 15 '26 09:09

Gyuhyeon Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!