Skip to content

Instantly share code, notes, and snippets.

@huzemin
Created July 30, 2016 07:44
Show Gist options
  • Save huzemin/86e4bbebf456d17af9f24e455254e986 to your computer and use it in GitHub Desktop.
Save huzemin/86e4bbebf456d17af9f24e455254e986 to your computer and use it in GitHub Desktop.
Node Pipe to TTY
function shell(cmd, opts, callback) {
var p = spawn(cmd, opts, { customFds: [0, 1, 2] });
//process.stdin.pause();
return p.on('exit', function() {
//process.stdin.resume();
return callback();
});
}
//var mintty = shell('cmd', ['/k', 'node', 'minttyshim.js'], function(){ return process.exit() });
var mintty = shell('node', ['minttyshim.js'], function(){ return process.exit() });
var tty = require('../core/TTY');
var util = require('util');
var TTY = process.binding('tty_wrap');
var EventEmitter = require('events').EventEmitter;
// method 1: create new streams
var stdin = new tty.ReadStream(0);
var stdout = new tty.WriteStream(1);
var stderr = new tty.WriteStream(2);
EventEmitter.call(stdin);
EventEmitter.call(stdout);
EventEmitter.call(stderr);
// method 2: monkeypatch existing ones
tty.ReadStream.call(process.stdin);
tty.WriteStream.call(process.stdout);
process.stdin.__proto__ = tty.ReadStream.prototype;
process.stdout.__proto__ = tty.WriteStream.prototype;
process.stdin._handle.__proto__ = TTY.prototype;
process.stdout._handle.__proto__ = TTY.prototype;
var UltraREPL = require('../');
new UltraREPL
var tty = require('tty');
var TTY = process.binding('tty_wrap').TTY;
var net = require('net');
module.exports = {
ReadStream: ReadStream,
WriteStream: WriteStream,
isatty: function isatty(fd){
return tty.isatty(fd);
},
setRawMode: function setRawMode(flag){
process.stdin._handle.setRawMode(flag);
}
}
function ReadStream(fd){
tty.ReadStream.apply(this, arguments);
}
ReadStream.prototype = {
constructor: ReadStream,
__proto__: tty.ReadStream.prototype,
isTTY: true,
pause: function pause(){
this._handle.unref();
return net.Socket.prototype.pause.call(this);
},
resume: function resume(){
this._handle.ref();
return net.Socket.prototype.resume.call(this);
}
};
function WriteStream(fd) {
tty.WriteStream.apply(this, arguments);
}
WriteStream.prototype = {
constructor: WriteStream,
__proto__: tty.WriteStream.prototype,
isTTY: true,
cursorTo: function cursorTo(x, y) {
if (typeof x !== 'number' && typeof y !== 'number')
return;
if (typeof x !== 'number')
throw new Error("Can't set cursor row without also setting it's column");
if (typeof y !== 'number') {
this.write('\x1b[' + (x + 1) + 'G');
} else {
this.write('\x1b[' + (y + 1) + ';' + (x + 1) + 'H');
}
},
moveCursor: function moveCursor(dx, dy) {
if (dx < 0) {
this.write('\x1b[' + (-dx) + 'D');
} else if (dx > 0) {
this.write('\x1b[' + dx + 'C');
}
if (dy < 0) {
this.write('\x1b[' + (-dy) + 'A');
} else if (dy > 0) {
this.write('\x1b[' + dy + 'B');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment