Skip to content

Instantly share code, notes, and snippets.

@DannyNemer
Last active September 20, 2015 18:06
Show Gist options
  • Select an option

  • Save DannyNemer/29dc7b636e3518071e6f to your computer and use it in GitHub Desktop.

Select an option

Save DannyNemer/29dc7b636e3518071e6f to your computer and use it in GitHub Desktop.
An extension of Node's Readline interface enabling the re-opening of an `Interface` instance after `rl.close()`
var readline = require('readline')
var rl = readline.createInterface(process.stdin, process.stdout)
// Re-opens the readline `Interface` instance. Regains control of the `input` and `output` streams
// by restoring listeners removed by the "close" event.
rl.reopen = (function () {
// Change one time event listener for "close" event to a normal event listener.
var onclose = rl.listeners('close')[0]
rl.removeListener('close', onclose)
rl.on('close', onclose.listener)
// Save the `input` and `output` listeners which are removed by the "close" event.
var onkeypress = rl.input.listeners('keypress')[0]
var ontermend = rl.input.listeners('end')[1]
var onresize = rl.output.listeners('resize')[0]
return function () {
if (!this.closed) return
this.resume()
if (this.terminal) {
this._setRawMode(true)
}
this.closed = false
// Restore `input` listeners.
this.input.on('keypress', onkeypress)
this.input.on('end', ontermend)
// Restore `output` listener.
if (this.output !== null && this.output !== undefined) {
this.output.on('resize', onresize)
}
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment