Skip to content

Commit

Permalink
readline based basic implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Yanis Benson committed Oct 5, 2019
1 parent de85060 commit 8e230b9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 45 deletions.
66 changes: 21 additions & 45 deletions index.js
@@ -1,39 +1,21 @@
'use strict';
const readline = require('readline');

const chalk = require('chalk');
const cliCursor = require('cli-cursor');
const cliSpinners = require('cli-spinners');
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() {
Expand All @@ -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;
}
}

Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -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"
},
Expand Down

0 comments on commit 8e230b9

Please sign in to comment.