« get me outta code hell

crawl-youtube.js « src - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/src/crawl-youtube.js
blob: 823fef7dd5e5fa0bda5a6eedd42c1d2ae55f376e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
'use strict'

const { spawn } = require('child_process')
const promisifyProcess = require('./promisify-process')

async function crawl(url) {
  const ytdl = spawn('youtube-dl', [
    '-j', // Output as JSON
    '--flat-playlist',
    url
  ])

  const items = []

  ytdl.stdout.on('data', data => {
    const lines = data.toString().trim().split('\n')

    items.push(...lines.map(JSON.parse))
  })

  // Don't show logging.
  await promisifyProcess(ytdl, false)

  return {
    items: items.map(item => {
      return {
        name: item.title,
        downloaderArg: 'https://youtube.com/watch?v=' + item.id
      }
    })
  }
}

async function main(args) {
  // TODO: Error message if none is passed.

  if (args.length === 0) {
    console.error("Usage: crawl-youtube <playlist URL>")
  } else {
    console.log(JSON.stringify(await crawl(args[0]), null, 2))
  }
}

module.exports = main

if (require.main === module) {
  main(process.argv.slice(2))
    .catch(err => console.error(err))
}