summaryrefslogtreecommitdiff
path: root/deps/node/deps/npm/node_modules/npm-lifecycle/lib/spawn.js
blob: 30e5b81846977a26ef0742b3af65c3d16da3acd1 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
'use strict'

module.exports = spawn

const _spawn = require('child_process').spawn
const EventEmitter = require('events').EventEmitter

let progressEnabled
let running = 0

function startRunning (log) {
  if (progressEnabled == null) progressEnabled = log.progressEnabled
  if (progressEnabled) log.disableProgress()
  ++running
}

function stopRunning (log) {
  --running
  if (progressEnabled && running === 0) log.enableProgress()
}

function willCmdOutput (stdio) {
  if (stdio === 'inherit') return true
  if (!Array.isArray(stdio)) return false
  for (let fh = 1; fh <= 2; ++fh) {
    if (stdio[fh] === 'inherit') return true
    if (stdio[fh] === 1 || stdio[fh] === 2) return true
  }
  return false
}

function spawn (cmd, args, options, log) {
  const cmdWillOutput = willCmdOutput(options && options.stdio)

  if (cmdWillOutput) startRunning(log)
  const raw = _spawn(cmd, args, options)
  const cooked = new EventEmitter()

  raw.on('error', function (er) {
    if (cmdWillOutput) stopRunning(log)
    er.file = cmd
    cooked.emit('error', er)
  }).on('close', function (code, signal) {
    if (cmdWillOutput) stopRunning(log)
    // Create ENOENT error because Node.js v8.0 will not emit
    // an `error` event if the command could not be found.
    if (code === 127) {
      const er = new Error('spawn ENOENT')
      er.code = 'ENOENT'
      er.errno = 'ENOENT'
      er.syscall = 'spawn'
      er.file = cmd
      cooked.emit('error', er)
    } else {
      cooked.emit('close', code, signal)
    }
  })

  cooked.stdin = raw.stdin
  cooked.stdout = raw.stdout
  cooked.stderr = raw.stderr
  cooked.kill = function (sig) { return raw.kill(sig) }

  return cooked
}