« get me outta code hell

promisify-process.js « src - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/src/promisify-process.js
blob: 4d06f8c66fd939684cc03f4a7dd30abf5453b317 (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
'use strict'

const { Writable } = require('stream')

module.exports = function promisifyProcess(proc, showLogging = true) {
  // Takes a process (from child_process) and returns a promise that resolves
  // when the process exits (or rejects with a warning, if the exit code is
  // non-zero).

  return new Promise((resolve, reject) => {
    if (showLogging) {
      proc.stdout.pipe(process.stdout)
      proc.stderr.pipe(process.stderr)
    } else {
      // For some mysterious reason, youtube-dl doesn't seem to work unless
      // we pipe the output of it SOMEWHERE..

      const emptyStream = () => Object.assign(new Writable(), {
        write: () => {}
      })

      proc.stdout.pipe(emptyStream())
      proc.stderr.pipe(emptyStream())
    }

    proc.on('exit', code => {
      if (code === 0) {
        resolve()
      } else {
        console.error("Process failed!", proc.spawnargs)
        reject(code)
      }
    })
  })
}