Search code examples
node.jsexpressproxymjpeg

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


Solution

  • 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();
        }
    });