How to fetch a video from a remote server and pipe it to the client (browser) using nodejs http?

Viewed 669

I have the following code to fetch a video from a remote url and then play it in the browser:

const express = require('express')
const http = require('https')
const url = 'https://www.exmaple.com/video.mp4'
const app = express()
const port = 3000
const url = require('url')

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/player.html')  //simple html document that contains a <video>
                                              // tag and it's 'src' is '/bro'
})

app.get('/bro', (req, res) => {       //this request is made by the <video> tag in the player.html file
    http.get(url, (response) => {
        response.pipe(res)
    })
})

but, the player hangs for like 45 seconds before it starts playing the video, and if the video duration was like 40 minutes or more, the player only plays the first 3 minutes of it.

MY QUESTION IS: How can I use the 'data' event on the http response to play or pipe that incoming chunks of data to the browser?

Is there a way to process those chunks to make them playable and pass the to the browser?

I used it like the following and It didn't work.

app.get('/bro', (req, res) => {
    http.get(url, (response) => {
        response.on('data', (data) => {
            data.pipe(res)
        })
    })
})
0 Answers
Related