Skip to content

Instantly share code, notes, and snippets.

@shikhir-arora
Last active August 6, 2017 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shikhir-arora/00749ad27f62c9c0db18ee1548a41244 to your computer and use it in GitHub Desktop.
Save shikhir-arora/00749ad27f62c9c0db18ee1548a41244 to your computer and use it in GitHub Desktop.
Return related YouTube track for AutoPlay (ES8)
const cheerio = require('cheerio')
async function relatedTrackAuto () {
let request = require('async-request')
try {
let response = await request(process.argv[2])
var $ = await cheerio.load(response.body)
let urlres = await $(`.video-list>.video-list-item>.content-wrapper>.content-link`).attr(`href`)
let finalres
if (urlres === undefined) {
finalres = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
console.log(`Undefined URL. Defaulting to Rick Roll!`)
return finalres
} else {
finalres = 'https://www.youtube.com' + urlres
return finalres
}
} catch (error) {
console.log(error)
return null
}
}
relatedTrackAuto()
.then(function (result) {
console.log(result)
})
@shikhir-arora
Copy link
Author

shikhir-arora commented Aug 6, 2017

Notes

  • Two options: as it is above, with https://gist.github.com/shikhir-arora/00749ad27f62c9c0db18ee1548a41244#file-relatedyoutube-js-L7 on line 7, the script will expect a valid URL (any URL) as a command argument in a terminal. The usage is node relatedYoutube.js "http://youtube.link.here" which will return the related song URL.

  • Removing line 7 and changing it back to simply let response = await request('URL_HERE') -- can use whatever fits the need to pass in the URL field.
    process.argv[2] just makes it easy to do quick terminal commands with any URL before integration.

  • async-request to make our lives easier. I have an updated version which can be installed manually or with
    { "async-request": "github:shikhir-arora/async-request" } as a dependency in your package file. Here is my fork: https://github.com/shikhir-arora/async-request which just ensures things are up-to-date for this use.
    (it is just a basic extension of request and saves a few lines of code).

  • Code is written in StandardJS -style for Node v8+ and is all ES8. Linted and Syntax verified against my standard ES8/Node config

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment