summaryrefslogtreecommitdiff
path: root/deps/npm/node_modules/read/lib/read.js
blob: 92ed415726107671ebc0aa7ce25bcf7bb33530d0 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const readline = require('readline')
const Mute = require('mute-stream')

module.exports = async function read ({
  default: def = '',
  input = process.stdin,
  output = process.stdout,
  completer,
  prompt = '',
  silent,
  timeout,
  edit,
  terminal,
  replace,
}) {
  if (typeof def !== 'undefined' && typeof def !== 'string' && typeof def !== 'number') {
    throw new Error('default value must be string or number')
  }

  let editDef = false
  prompt = prompt.trim() + ' '
  terminal = !!(terminal || output.isTTY)

  if (def) {
    if (silent) {
      prompt += '(<default hidden>) '
    } else if (edit) {
      editDef = true
    } else {
      prompt += '(' + def + ') '
    }
  }

  const m = new Mute({ replace, prompt })
  m.pipe(output, { end: false })
  output = m

  return new Promise((resolve, reject) => {
    const rl = readline.createInterface({ input, output, terminal, silent: true, completer })
    const timer = timeout && setTimeout(() => onError(new Error('timed out')), timeout)

    output.unmute()
    rl.setPrompt(prompt)
    rl.prompt()

    if (silent) {
      output.mute()
    } else if (editDef) {
      rl.line = def
      rl.cursor = def.length
      rl._refreshLine()
    }

    const done = () => {
      rl.close()
      clearTimeout(timer)
      output.mute()
      output.end()
    }

    const onError = (er) => {
      done()
      reject(er)
    }

    rl.on('error', onError)
    rl.on('line', (line) => {
      if (silent && terminal) {
        output.unmute()
      }
      done()
      // truncate the \n at the end.
      const res = line.replace(/\r?\n?$/, '') || def || ''
      return resolve(res)
    })

    rl.on('SIGINT', () => {
      rl.close()
      onError(new Error('canceled'))
    })
  })
}