« get me outta code hell

crawl-local.js « src - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/src/crawl-local.js
blob: 629e015f83ac5a0bdcc1071c86ed9dfa0fad70b8 (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
#!/usr/bin/env node

'use strict'

const fs = require('fs')
const path = require('path')
const naturalSort = require('node-natural-sort')

const { promisify } = require('util')
const readDir = promisify(fs.readdir)
const stat = promisify(fs.stat)

function crawl(dirPath) {
  return readDir(dirPath).then(items => {
    items.sort(naturalSort())

    return Promise.all(items.map(item => {
      const itemPath = path.join(dirPath, item)

      return stat(itemPath).then(stats => {
        if (stats.isDirectory()) {
          return crawl(itemPath)
            .then(group => Object.assign(group, {name: item}))
        } else if (stats.isFile()) {
          const track = {name: item, downloaderArg: itemPath}
          return track
        }
      })
    }))
  }).then(items => ({items}))
}

async function main(args) {
  if (args.length === 0) {
    console.log("Usage: crawl-local /example/path")
  } else {
    const path = args[0]

    const res = await crawl(path)
    console.log(JSON.stringify(res, null, 2))
  }
}

module.exports = main

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