Download video raw content in memory like this:
const downloadNew = () => {
http.get(urlFinal, (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
}
if (error) {
console.error(error.message);
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
console.log(rawData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
}
You can do it using node-fetch as well as with nodejs native code. I'll demonstrate both ways of downloading content in Nodejs (with/without using third party Libs):
Download using Node-Fetch library:
const http = require('http');
const fs = require('fs');
const urlFinal = 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4';
const util = require("util");
const fetch = require("node-fetch");
const newFilePath = "/home/amulyakashyap/Desktop/download/BigBuckBunny.mp4";
const downloadUsingFetch => ()=>{
fetch(urlFinal)
.then(res => {
const dest = fs.createWriteStream(newFilePath);
res.body.pipe(dest);
}).then(()=>console.log("finished"))
.catch(console.error);
}
Download using Native Nodejs (without third party lib support):
const downloadUsingNative = function(cb) {
let file = fs.createWriteStream(newFilePath);
let request = http.get(urlFinal, function(response) {
response.pipe(file);
file.on('finish', function() {
console.log("done")
file.close(cb);
});
}).on('error', function(err) {
fs.unlink(dest);
if (cb) cb(err.message);
});
};
const downloadUsingNativePromisified = util.promisify(downloadUsingNative);
downloadUsingNativePromisified().then(console.log).catch(console.error);