Skip to content

Instantly share code, notes, and snippets.

@ThunderWiring
Last active September 14, 2018 21:51
Show Gist options
  • Save ThunderWiring/a1a442dea9dc7e39932aca084920fc11 to your computer and use it in GitHub Desktop.
Save ThunderWiring/a1a442dea9dc7e39932aca084920fc11 to your computer and use it in GitHub Desktop.
how to donload a video form Youtube using ytdl-core in MP4 format
/**
* Checks if the title is valid for being a file name, otherwise, removes the
* characters that invalidates it.
* A valid file name, is a string that does not contain any of the following:
* / \ : * ? " < > |
* @param {string} title
* @return {string}
* @private
*/
validateFileName_(title) {
return title.replace(/[/\:*?"<>|]]/, '');
}
/**
* @param {string} userProvidedPath
* @param {string} title
* @private
*/
downloadVideoAsMp4_(userProvidedPath, title) {
return new Promise((resolve, reject) => {
const filename = this.validateFileName_(title);
let fullPath = `${userProvidedPath}/${filename}.mp4`;
// Create a reference to the stream of the video being downloaded.
let videoObject = Ytdl(this.youtubeUrl_, {
filter: 'audioonly',
quality: 'highestaudio'
});
videoObject
.on('progress', (chunkLength, downloaded, total) => {
//TODO: send event to UI to update progress
});
videoObject
.pipe(fs.createWriteStream(fullPath))
.on('finish', () => {
setTimeout(() => {
resolve({
filePath: fullPath,
folderPath: userProvidedPath,
fileTitle: `${title}.mp3`,
});
}, 1000);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment