From 8e230b983a3b044c6a8fd17d6fe71afa86e32c2c Mon Sep 17 00:00:00 2001 From: Yanis Benson Date: Sat, 5 Oct 2019 16:37:35 +0300 Subject: [PATCH] readline based basic implementation --- index.js | 66 +++++++++++++++++----------------------------------- package.json | 1 + 2 files changed, 22 insertions(+), 45 deletions(-) diff --git a/index.js b/index.js index 24995a0..85a5049 100644 --- a/index.js +++ b/index.js @@ -1,4 +1,6 @@ 'use strict'; +const readline = require('readline'); + const chalk = require('chalk'); const cliCursor = require('cli-cursor'); const cliSpinners = require('cli-spinners'); @@ -6,34 +8,14 @@ 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 TEXT = Symbol('text'); const PREFIX_TEXT = Symbol('prefixText'); -const noop = () => {}; -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 +41,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; } } diff --git a/package.json b/package.json index 1880f1e..c7c784c 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,7 @@ "cli-spinners": "^2.2.0", "is-interactive": "^1.0.0", "log-symbols": "^3.0.0", + "mute-stream": "0.0.8", "strip-ansi": "^5.2.0", "wcwidth": "^1.0.1" },