Skip to content

Instantly share code, notes, and snippets.

@brunocroh
Last active July 31, 2023 22:42
Show Gist options
  • Save brunocroh/b20424e06cff7ca74fdad152fa3cb131 to your computer and use it in GitHub Desktop.
Save brunocroh/b20424e06cff7ca74fdad152fa3cb131 to your computer and use it in GitHub Desktop.
Youtube downloader
import cliProgress from 'cli-progress'
import colors from 'ansi-colors'
import stream from 'stream'
async function endDownload(promise: any) {
return new Promise((resolve, reject) => {
promise
.then(resolve)
.catch(reject)
})
}
export async function progressBar(promise: any) {
let prevProgressNum = 0
const progressBar = new cliProgress.SingleBar({
format: `Downloading youtube Video | ${colors.bgRed('{bar}')} | {percentage}% | {value}/{total} Chunks`,
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
hideCursor: true
}, cliProgress.Presets.shades_classic);
progressBar.start(100, 0)
const stdoutStream = new stream.PassThrough();
promise?.stdout?.pipe(stdoutStream)
promise?.stdout?.on('data', () => {
try {
const output = stdoutStream.read().toString()
if (output) {
const match = output.match(/\b(\d{1,2}(?:\.\d{1,2})?)%/);
const percentage = match ? match[1] : null;
if (percentage) {
const num = Number(percentage)
if (Number.isInteger(num) && num > prevProgressNum) {
progressBar.update(Math.round(num))
prevProgressNum = num
}
}
}
} catch(err) {
console.error(err)
}
})
const result = await endDownload(promise)
progressBar.update(100)
progressBar.stop()
return result
}
import youtubedl from 'youtube-dl-exec';
import { progressBar } from './progressBar';
type GetVideo = {
url: string;
name: string;
folder: string;
};
export async function getVideo({ url, name, folder }: GetVideo) {
try {
const promise = youtubedl.exec(url, {
output: `./videos/${folder}/${name || '%(title)s'}.%(ext)s`,
format: 'mp4/bestvideo',
});
const result = await progressBar(promise);
} catch (error) {
console.log(error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment