Moved download function to its own file

This commit is contained in:
Supositware 2023-03-20 03:58:21 +01:00
parent c237f2fb7c
commit a0de902935
2 changed files with 36 additions and 30 deletions

34
scripts/downloadutils.js Normal file
View file

@ -0,0 +1,34 @@
import fs from 'node:fs';
import https from 'node:https';
export default {
download,
};
async function download(url, output) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
if (res.statusCode === 301 || res.statusCode === 302) {
console.log(`${output} download url: ${res.headers.location}`);
return download(res.headers.location, output);
}
const path = output;
const tmpPath = `${output}.new`;
const filePath = fs.createWriteStream(tmpPath);
res.pipe(filePath);
filePath.on('finish', () => {
filePath.close();
fs.renameSync(tmpPath, path);
fs.chmodSync(path, '755');
console.log(`${url} download finished.`);
resolve(true);
});
filePath.on('error', (err) => {
filePath.close();
reject(err);
});
});
});
}

View file

@ -1,5 +1,4 @@
import fs from 'node:fs';
import https from 'node:https';
import utils from './downloadutils.js';
if (process.platform !== 'linux' && process.argv[2] !== '-f') {
console.error('This script only download the linux version of yt-dlp. If you want to download anyway try again with -f');
@ -11,31 +10,4 @@ else if (process.platform !== 'linux' && process.argv[2] === '-f') {
const downloadUrl = 'https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp';
download(downloadUrl);
async function download(url) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
if (res.statusCode === 301 || res.statusCode === 302) {
console.log(`yt-dlp download url: ${res.headers.location}`);
return download(res.headers.location);
}
const tmpPath = './bin/yt-dlp.new';
const path = './bin/yt-dlp';
const filePath = fs.createWriteStream(tmpPath);
res.pipe(filePath);
filePath.on('finish', () => {
filePath.close();
fs.renameSync(tmpPath, path);
fs.chmodSync('./bin/yt-dlp', '755');
console.log('yt-dlp download finished.');
resolve(true);
});
filePath.on('error', (err) => {
filePath.close();
reject(err);
});
});
});
}
utils.download(downloadUrl, './bin/yt-dlp');