I have made a program where users provide a YouTube channel URL and in return I will show the user its channel ID.
Like if someone puts URL like: https://youtube.com/@AndreoBee then I will return its channel ID.
const axios = require('axios');
async function getChannelId(url) {
const channelUsername = url.split('/').pop();
const response = await axios.get(`https://www.googleapis.com/youtube/v3/channels?part=id&forUsername=${channelUsername}&key=myapi`);
if (response.data.items.length === 0) {
throw new Error(`Channel not found: ${url}`);
}
console.log(response.data.items[0].id);
}
getChannelId('https://www.youtube.com/@AndreoBee');
Output:
/home/runner/ytcheck/index.js:7 if (response.data.items.length === 0) { ^
TypeError: Cannot read properties of undefined (reading 'length') at getChannelId (/home/runner/ytcheck/index.js:7:27)
You can try the following node.js script
var https = require('https');
var url = "https://www.youtube.com/@adnantoky"
https.get(url, function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
let arr = data.split('channel_id=');
console.log("Channel ID:", arr[1].slice(0, 24));
});
}).on('error', function (e) {
console.log(e.message);
});