Search code examples
node.jsvideodownloadmp43gp

How to programatically download a video?


I'm trying to programmatically download a video file from a web-server through a link.

If you'd click that link through a web-browser it would just prompt you to download the video and to provide a name for the file and then download the video properly.

I have some nodejs code that just makes an HTTP request to that link and successfully gets raw data from it and saves it to a default file video.mp4

const https = require('https');
const fs = require('fs');

https.get('https://url.tocdn.com/myvideoid', (resp) => {
let data = '';

// A chunk of data has been recieved.
resp.on('data', (chunk) => {
    data += chunk;
});

// The whole response has been received. Print out the result.
resp.on('end', () => {
    fs.writeFile('./video.mp4', data, (err) => console.log(err))
});

}).on("error", (err) => {
console.log("Error: " + err.message);
});

The problem is that when I try to play that file through Windows Media Player, for example, it just shows an error regarding the file format. Am I missing something obvious?


Solution

  • Don't use string if you're pretending to store bytes,

    or application/octet-stream in my case (which is the same)

    From the given snippet change:

    resp.on('data', (chunk) => {
        data = Buffer.concat([data, Buffer.from(chunk)]);
    });
    

    And make sure to initialize data as follows: let data = Buffer.from([]);