All files childProcess.js

0% Statements 0/24
0% Branches 0/4
0% Functions 0/12
0% Lines 0/19
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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                                                                                                                                         
// @flow
 
import {
  exec,
  spawn
} from 'child_process'
import type {
  ChildProcess
} from 'child_process'
 
type ExecOpts = {
  cwd?: string;
  env?: Object;
  encoding?: string;
  shell?: string;
  timeout?: number;
  maxBuffer?: number;
  killSignal?: string;
  uid?: number;
  gid?: number;
}
 
type SpawnOpts = {
  cwd?: string;
  env?: Object;
  argv0?: string;
  stdio?: string | Array<any>;
  detached?: boolean;
  uid?: number;
  gid?: number;
  shell?: boolean | string;
}
 
export function promisifyChildProcess (child: ChildProcess) : Promise<void> {
  return new Promise((resolve, reject) => {
    child.addListener('error', err => reject(err))
    child.addListener('exit', code => {
      if (code === 0) {
        resolve()
      } else {
        reject(new Error(`ChildProcess exited with code ${code}`))
      }
    })
  })
}
 
export async function execp (command: string, options?: ExecOpts) : Promise<string | Buffer> {
  log.trace(`execp => command: ${command} options: ${JSON.stringify(options)}`)
  return new Promise((resolve, reject) => {
    const cp = exec(command, options, (error, stdout, stderr) => {
      if (error) {
        reject(error)
      } else {
        resolve(stdout)
      }
    })
    cp.stdout.on('data', data => log.trace(data))
    cp.stderr.on('data', data => log.debug(data))
  })
}
 
export async function spawnp (command: string, args?: string[], options?: SpawnOpts) {
  log.trace(`spawnp => command: ${command} args: ${JSON.stringify(args)} options: ${JSON.stringify(options)}`)
  const cp = spawn(command, args, options)
  cp.stdout.on('data', data => log.trace(data))
  cp.stderr.on('data', data => log.debug(data))
  return promisifyChildProcess(cp)
}