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 9ef2c55
Showing 1 changed file with 20 additions and 42 deletions.
62 changes: 20 additions & 42 deletions index.js
Expand Up @@ -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');
Expand All @@ -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() {
Expand All @@ -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;
}
}

Expand Down

0 comments on commit 9ef2c55

Please sign in to comment.