« 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: 4c510a1eb877e21ab2385786d2311c26b0ecdf71 (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
#!/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(contents => {
            const group = [item, contents]
            return group
          })
        } else if (stats.isFile()) {
          const track = [item, itemPath]
          return track
        }
      })
    }))
  })
}

if (process.argv.length === 2) {
  console.log("Usage: http-music-crawl-local /example/path..")
  console.log("..or, npm run crawl-local /example/path")
} else {
  const path = process.argv[2]

  crawl(path)
    .then(res => console.log(JSON.stringify(res, null, 2)))
    .catch(err => console.error(err))
}