Skip to content

Instantly share code, notes, and snippets.

@PapsOu
Created Dec 13, 2019
Embed
What would you like to do?
A simple javascript (node) script used to download items of a youtube playlist as audio files
//
// Dependency : [youtube-dl](https://github.com/ytdl-org/youtube-dl)
//
// How to use :
//
// - install targetFolder : `pip install --upgrade youtube-dl`
// - Go to a YouTube playlist (eg: https://www.youtube.com/playlist?list=PLzCxunOM5WFLNCSF0UEHZqFJJlmdeL71S)
// - The ID is `PLzCxunOM5WFLNCSF0UEHZqFJJlmdeL71S`
// - Update the const `playlistId`.
// - Grab a YouTube Data API token in https://console.developers.google.com
// - Update the const `key`
// - [Optional]: change the const `targetFolder` to put audio files in another folder than the default one (current script path).
// - Execute the script : `node ./yt.js`
// - Be patient, it will take a long time to download, especially if the playlist has much items..
//
// Config
const host = 'https://www.googleapis.com/youtube/v3'
const watchUrl = 'https://www.youtube.com/watch?v='
const key = '<YOUR_YOUTUBE_API_KEY>'
const playlistId = '<TARGET_PLAYLIST_ID>'
const targetFolder = 'mp3'
// Libs
const https = require('https');
const { spawnSync } = require( 'child_process' );
// Data
var commands = []
// Base functions
function GET(path, params, callback) {
let urlParams = ''
for (let key in params) {
urlParams = urlParams
.concat('&')
.concat(key)
.concat('=')
.concat(params[key])
}
console.log(host + path + '?key=' + key + urlParams)
https.get(host + path + '?key=' + key + urlParams, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
callback(JSON.parse(data))
})
})
}
function fetchPage(pageToken, callback) {
let params = {
playlistId: playlistId,
part: 'contentDetails',
maxResults: 50
}
if (pageToken !== undefined) {
params.pageToken = pageToken
}
GET('/playlistItems', params, (data) => {
for (let item of data.items) {
let command = [
'youtube-dl',
'-x',
'--audio-quality', '0',
'--audio-format', 'mp3',
'-o', targetFolder + '/%(title)s-%(id)s.%(ext)s',
watchUrl + item.contentDetails.videoId
]
commands.push(command)
}
if (data.nextPageToken !== undefined) {
fetchPage(data.nextPageToken, callback)
} else {
callback()
}
})
}
// Main
fetchPage(undefined, function() {
for (let cmd of commands) {
console.log('spawning ' + cmd.join(' '))
const extracting = spawnSync(cmd.shift(), cmd)
console.log(extracting.stderr.toString())
console.log(extracting.stdout.toString())
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment