Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a bash wrapper in NodeJS process

I want to build a tiny script that being run should create a bash-like session (in the current bash session, where the process is created), that can be used later for some mad science (e.g. piping to browser).

I tried using pty.js, piping stdin to the bash process, and data from the bash session to the stdout stream:

var pty = require("pty.js");

var term = pty.spawn('bash', [], {
  name: 'xterm-color',
  cols: process.stdout.columns,
  rows: process.stdout.rows,
  cwd: ".",
  env: process.env
});

term.pipe(process.stdout);
process.stdin.pipe(term);

term.on("close", function () {
    process.exit();
});

This works, but it's very buggy:

For example, the non-characters (directional keys, tab etc) are not caught.

I also tried using spawn, this not being so bad, but still buggy.

var spawn = require("child_process").spawn;

var bash = spawn("bash");
bash.stdout.pipe(process.stdout);
process.stdin.pipe(bash.stdin);

Is there a better solution how to create a bash wrapper in NodeJS?

like image 936
Ionică Bizău Avatar asked Feb 12 '15 14:02

Ionică Bizău


1 Answers

You might want to put the standard input into raw mode. This way all the key strokes will be reported as a data event. Otherwise you only get lines (for every press of the return key).

process.stdin.setEncoding('utf8');
process.stdin.setRawMode(true);      

var pty = require('pty.js');

var term = pty.spawn('bash', [], {
   name: 'xterm-color',
   cols: process.stdout.columns,
   rows: process.stdout.rows,
   cwd: '.',
   env: process.env
});

term.pipe(process.stdout);
process.stdin.pipe(term);

term.on('close', function () {
    process.exit();
});

Maybe you also find some more experience from other in this related question.

PS: Vim runs now much better :P

like image 101
4 revs, 2 users 76% Avatar answered Sep 30 '22 13:09

4 revs, 2 users 76%