Nodejsでyoutubeの動画をダウンロードする
NodejsからYoutubeの動画をダウンロードできるようなモジュールがないかなーとさがしていたところytdl-coreというモジュールが非常に使いやすかったので、nodejsのWebフレームワークでお馴染みのExpressと組み合わせて、Youtubeの動画をダウンロードするアプリケーションを作ってみました。
ytdlの使い方
インストールはいつも通りのNPMコマンドでできます。たまにYoutube側の通信規格の変更で使えなくなるので、使えなくなったときはアップデートを掛けましょう。
# youtube-coreのインストール $ npm install ytdl-core
ytdlとExpressで動画ダウンロードアプリを作成する
このYoutube-coreとNodejsのフレームワークである「Express」を使ってYoutubeの動画をダウンロードするアプリケーションを作っていきます。
<index.js>
const express = require('express');
const cors = require('cors');
const ytdl = require("ytdl-core");
const app = express();
app.use(cors());
app.listen(3000, () => {
console.log('Server Works !!! At port 3000');
});
app.get('/', (req, res) => {
res.send('ページが表示されました!')
})
app.get("/download", (req, res) => {
var URL = req.query.url;
console.log("url", URL);
var stream = ytdl(URL);
stream.on('info', (info) => {
console.log(info.title);
console.log(info.video_id);
res.header('Content-Disposition', 'attachment; filename="video.mp4"');
ytdl(URL, {
format: 'mp4'
}).pipe(res);
});
});
<index.html>
<!DOCTYPE html>
<html>
<head>
<title>YouTube ダウンローダー</title>
<link rel="stylesheet" href="./static/css/style.css">
</head>
<body>
<h1 class="heading">YouTube ダウンローダー</h1>
<form action="http://127.0.0.1:3000/download" method="get">
<input class="URL-input" name='url' placeholder="Video URL e.g. https://www.youtube.com/watch?v=MtN1YnoL46Q">
<button type='submit' class="convert-button">mp4</button></a>
</form>
</body>
<script src='./static/js/script.js'></script>
</html>
<style.css>
* {
text-align: center;
}
.heading {
font-family: Arial;
margin-top: 40vh;
}
.URL-input,
.convert-button {
font-size: 1.3em;
padding: 5px 10px;
}
.URL-input {
border-radius: 4px 0px 0px 4px;
width: 30em;
text-align: left;
border: 2px solid #EEEEEE;
background: #EEEEEE;
outline: none;
}
.URL-input:focus {
border: 2px solid #0485ff;
}
.convert-button {
border-radius: 0px 4px 4px 0px;
border: 2px solid #0485ff;
background: #0485ff;
color: white;
}
<script.js>
var convertBtn = document.querySelector('.convert-button');
var URLinput = document.querySelector('.URL-input');
convertBtn.addEventListener('click', () => {
console.log(`URL: ${URLinput.value}`);
});
index.htmlをクリックしてブラウザで見ると以下のような感じになっています。

ここの入力フォームにYoutubeの動画URLを張り付けてMP4のボタンをクリックするとダウンロードがはじまります。
このURL入力で注意して欲しいのはクエリにlistやindexなどの余分なクエリが付いているとダウンロードエラーになるので、純粋な動画IDだけを入力してください。
× https://www.youtube.com/watch?v=2FzlpZqyuKg&list=RDXhMX4tSbGnY&index=3
〇https://www.youtube.com/watch?v=2FzlpZqyuKg
【Github】https://github.com/beginerSE/express-ytdl
参考:
https://blog.hassler.ec/wp/2019/01/02/how-i-made-my-own-youtube-downloader-using-javascript-and-node-js/
https://stackoverflow.com/questions/44605425/download-a-youtube-video-file-in-node-js-using-ytdl:embed


コメント