Skip to content

Instantly share code, notes, and snippets.

@kadiks
Last active July 17, 2022 01:46
Show Gist options
  • Save kadiks/d2be3519df94dc90e0920234f1764f1b to your computer and use it in GitHub Desktop.
Save kadiks/d2be3519df94dc90e0920234f1764f1b to your computer and use it in GitHub Desktop.
Download YouTube playlists (2022)
// Installation
// -
// mkdir yt_download_playlist
// cd yt_download_playlist
// mkdir download
// npm init -y
// npm install puppeteer
// npm install ytdl-core
// touch index.js
// Paste the code in the `index.js`
// Usage
// -
// update playlistUrl variable with your playlist
// node index.js
const puppeteer = require("puppeteer");
const fs = require("fs");
const path = require("path");
const ytdl = require("ytdl-core");
const delay = (ms) => {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
};
const downloadVideo = (id, { folderPath = "", opts = {} } = {}) => {
return new Promise(async (resolve, reject) => {
const video = ytdl(`https://www.youtube.com/watch?v=${id}`, opts);
video.on("end", () => {
resolve();
});
video.pipe(fs.createWriteStream(path.join(folderPath, `${id}.mp4`)));
});
};
const start = async (url, { headless = true } = {}) => {
const browser = await puppeteer.launch({ headless });
const page = await browser.newPage();
await page.goto(url);
await delay(1000);
const links = await page.evaluate(() => {
return Array.from(
document.querySelectorAll("#playlist-items a#wc-endpoint")
).map((el) => el.href);
});
const ids = links.map((link) => {
return new URL(link).searchParams.get("v");
});
for (const id of ids) {
console.log("Downloading video:", id);
await downloadVideo(id, {
folderPath: "download",
});
console.log("END:", id);
}
console.log("Finished!");
await browser.close();
};
const playlistUrl = ""; // Change url here
start(playlistUrl, { headless: true });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment