UNPKG

2.04 kBJavaScriptView Raw
1const axios = require('axios');
2
3/**
4 * Search for YouTube videos by query string.
5 *
6 * @param {string} query - The search query string.
7 * @param {string} ogq - The original search query string (used for error messages).
8 * @returns {array} - An array of video data objects.
9 * @throws {Error} - If no results are found for the search query.
10 */
11const search = async (query, ogq) => {
12 const base = 'https://www.youtube.com/results';
13
14 const options = {
15 app: 'desktop',
16 search_query: query
17 };
18
19 try {
20 const response = await axios.get(base, { params: options });
21 const html = response.data;
22
23 // Parse the initial data object from the HTML response
24 const findInitialData = html.match(/var ytInitialData = {(.*?)};/g)[0];
25 const fixData = findInitialData.replace(/var ytInitialData = /g, '');
26 const initialData = JSON.parse(fixData.slice(0, -1));
27
28 // Find the array of video data objects in the initial data object
29 let data = initialData.contents.twoColumnSearchResultsRenderer.primaryContents.sectionListRenderer.contents;
30 let index, confirm = false;
31 for (let i = 0; i < data.length; i++) {
32 if (confirm) break;
33 if (data[i].hasOwnProperty('itemSectionRenderer')) {
34 for (let j = 0; j < data[i].itemSectionRenderer.contents.length; j++) {
35 if (data[i].itemSectionRenderer.contents[j].hasOwnProperty('videoRenderer')) {
36 index = i;
37 confirm = true;
38 break;
39 }
40 }
41 }
42 }
43
44 // If video data objects were found, return them. Otherwise, throw an error.
45 if (typeof data[index] === 'object' && data[index].hasOwnProperty('itemSectionRenderer')) {
46 data = data[index].itemSectionRenderer.contents;
47 return data;
48 } else {
49 throw new Error(`No results were found for search query '${ogq}'.`);
50 }
51 } catch (error) {
52 throw new Error(`Error searching for query '${ogq}': ${error.message}`);
53 }
54};
55
56module.exports = search;