Skip to content

Instantly share code, notes, and snippets.

@kallefrombosnia
Created July 26, 2021 20:14
Show Gist options
  • Save kallefrombosnia/8f8a92cac7814c3067693b1838edd1ea to your computer and use it in GitHub Desktop.
Save kallefrombosnia/8f8a92cac7814c3067693b1838edd1ea to your computer and use it in GitHub Desktop.
ytSearchWithoutAPI
const https = require('https');
/**
* Define our function
*/
const ytSearchResult = (song) =>{
// return promised result
return new Promise((resolve, reject) =>{
// Send get request to the youtube
https.get(`https://www.youtube.com/results?q=${encodeURIComponent(song)}&hl=en`, (res) => {
// Init data string
let data = '';
// Append data
res.on('data', (chunk) => {
data += chunk;
});
// Event fired on stream finish
res.on('end', () => {
// Our exporting id list
let idlist = [];
// Match all results
const ids = data.match(/{"url":"\/watch\?v=(.{11})"/g);
// Parse trough them and get id
ids.forEach((string, index) =>{
// Data is not well formated so we need to split returned string
idlist.push(string.split('=')[1]);
// Check if we have reached end of array
if((index + 1) === ids.length){
// If yes resolve with id array list
resolve(idlist);
}
});
});
}).on("error", (err) => {
reject(err);
});
});
}
// Call function
ytSearchResult('best song').then(data => {
// Log array id
console.log(data)
}).catch(err => console.log(err.toString()))
/**
* Example
*
* [
'NSRobDsUb54"', 'o_v9MY_FMcw"',
'k_on7zgBPUA"', 'qclWIFxq2F4"',
'lyIhRNPCNiw"', 'HPkydJOXXNs"',
'cW9EdTbkWfc"', '-ObdvMkCKws"',
'jRS6cGbr3Og"', 'LwOQdoYKQ5k"',
'HigTewy3OTM"', '5D8KR6_wPU0"',
'LpfMVFY1TOM"', 'AOMU6qcOFW0"',
'P51_8HMI150"', 'DQ2Ru2obvQE"',
'UgfsbL-uHOA"', '4HD_pJpQ4SQ"',
'X3e2oPpX5ek"', 'cWm8OXGUHZQ"',
'5mFTXbZzOAE"', 'nntmY825J64"',
'OlRKpevb-Gs"', 'GKSRyLdjsPA"',
'o_cikTgwMXY"', 'lbPhbuO4wc4"',
'Zf94v3vTGQc"', '7zT8omdej4c"'
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment