diff --git a/index.js b/index.js index 24995a0..b5406f6 100644 --- a/index.js +++ b/index.js @@ -6,6 +6,8 @@ const logSymbols = require('log-symbols'); const stripAnsi = require('strip-ansi'); const wcwidth = require('wcwidth'); const isInteractive = require('is-interactive'); +const MuteStream = require('mute-stream'); +const readline = require('readline'); const TEXT = Symbol('text'); const PREFIX_TEXT = Symbol('prefixText'); @@ -16,24 +18,6 @@ const ASCII_ETX_CODE = 0x03; // Ctrl+C emits this code class StdinDiscarder { constructor() { this.requests = 0; - - const self = this; - this.ourEmit = function (event, data, ...args) { - const {stdin} = process; - if (self.requests > 0 || stdin.emit === self.ourEmit) { - if (event === 'keypress') { // Fixes readline behavior - return; - } - - if (event === 'data' && data.includes(ASCII_ETX_CODE)) { - process.emit('SIGINT'); - } - - self.oldEmit.apply(this, [event, data, ...args]); - } else { - process.stdin.emit.apply(this, [event, data, ...args]); - } - }; } start() { @@ -59,35 +43,29 @@ class StdinDiscarder { realStart() { const {stdin} = process; - this.oldRawMode = stdin.isRaw; - this.oldEmit = stdin.emit; - this.oldEmitOwnProperty = Object.prototype.hasOwnProperty.call(stdin, 'emit'); + const output = new MuteStream(); + output.pipe(process.stdout); + output.mute(); - stdin.setRawMode(true); - stdin.on('data', noop); - stdin.resume(); + this.readline = readline.createInterface({ + input: stdin, + output + }); - stdin.emit = this.ourEmit; + this.readline.on('SIGINT', () => { + if (process.listenerCount('SIGINT') === 0) { + this.realStop(); // Need to add flag for that + process.kill(process.pid, 'SIGINT'); + } else { + process.emit('SIGINT'); + // This probably fails under windows + } + }); } realStop() { - const {stdin} = process; - - if (this.oldEmitOwnProperty) { - stdin.emit = this.oldEmit; - } else { - delete stdin.emit; - } - - this.oldRawMode = undefined; - this.oldEmit = undefined; - this.oldEmitOwnProperty = undefined; - - stdin.setRawMode(this.oldRawMode); - stdin.removeListener('data', noop); - if (stdin.listenerCount('data') === 0) { - stdin.pause(); - } + this.readline.close(); + this.readline = undefined; } }