From c26a07dc7335d8ddef1f9baeef4659020130998b Mon Sep 17 00:00:00 2001 From: LuanRT Date: Sat, 3 Sep 2022 16:28:18 -0300 Subject: [PATCH] docs: add a more complete download example --- examples/download/index.ts | 46 +++++++++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 13 deletions(-) diff --git a/examples/download/index.ts b/examples/download/index.ts index e0252835..51f600b4 100644 --- a/examples/download/index.ts +++ b/examples/download/index.ts @@ -1,24 +1,44 @@ -import { createWriteStream } from 'fs'; import { Innertube, UniversalCache } from 'youtubei.js'; +import { readFileSync, existsSync, mkdirSync, createWriteStream } from 'fs'; (async () => { const yt = await Innertube.create({ cache: new UniversalCache() }); - const info = await yt.getBasicInfo('jLTOuvBTLxA'); + const search = await yt.music.search('No Copyright Background Music', { type: 'album' }); - const stream = await info.download({ - type: 'audio', - quality: 'best', - format: 'mp4' - }); + if (!search.results) + throw new Error('Filter "type" must be used'); + + const album = await yt.music.getAlbum(search.results[0].id as string); - console.info(`Downloading ${info.basic_info.title}...`); - - const file = createWriteStream(`${info.basic_info.title}.m4a`); + if (!album.contents) + throw new Error('Album appears to be empty'); + + console.info(`Album "${album.header.title.toString()}" by ${album.header.author?.name}`, '\n'); - for await (const chunk of streamToIterable(stream)) { - file.write(chunk); + for (const song of album.contents) { + const stream = await yt.download(song.id as string, { + type: 'audio', // audio, video or audio+video + quality: 'best' // best, bestefficiency, 144p, 240p, 480p, 720p and so on. + format: 'mp4' // media container format + }); + + console.info(`Downloading ${song.title} (${song.id})`); + + const dir = `./${album.header.title.toString()}`; + + if (!existsSync(dir)) { + mkdirSync(dir); + } + + const file = createWriteStream(`${dir}/${song.title?.replace(/\//g, '')}.m4a`); + + for await (const chunk of streamToIterable(stream)) { + file.write(chunk); + } + + console.info(`${song.id} - Done!`, '\n'); } - console.info('Done!'); + console.info(`Downloaded ${album.header.song_count}!`); })(); \ No newline at end of file