2

I'm trying to open a unix text editor (nano in this case) by issuing following command in a Node.js script:

  if (process.argv[2] === 'edit') {
    require('child_process').spawn("sudo", ["nano", dbFile], {
      stdio: 'inherit'
    });
    process.exit(); // try to block here in order not to execute rest of code in this file
  }

This opens up nano, but both the text is weird and it doesn't let me write anything.

ceremcem
  • 3,900
  • 4
  • 28
  • 66
  • Really `("nano " + dbFile).split(' ')` should be `["nano", dbFile]`. – Dan D. Sep 25 '15 at 22:47
  • you are right, but they gives the same result in this case. I'll update question accordingly. – ceremcem Sep 25 '15 at 23:58
  • 2
    you might want to check out http://stackoverflow.com/questions/9122282/how-do-i-open-a-terminal-application-from-node-js, it's vi but the accepted answer talks about problems you may run into. Like having to capture your input from the parent node process and piping the stream into your nano child process. – Sgnl Sep 26 '15 at 00:33

2 Answers2

0

I changed it a bit. Added an event listener on data on the process you spawned.

var dbFile = 'lol.js';
var editorSpawn = require('child_process').spawn("nano", [dbFile], {
  stdio: 'inherit',
  detached: true
});

editorSpawn.on('data', function(data){
  process.stdout.pipe(data);
});

inside of the data listener, process.stdout.pipe is streaming the output of nano to the terminal.

added my own variables and removed sudo as it was giving me errors. you should be able to apply this to your code.

Sgnl
  • 1,808
  • 22
  • 30
0

Try using pty.js:

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 nano = pty.spawn('nano', [], {
   name: 'xterm-color',
   cols: process.stdout.columns,
   rows: process.stdout.rows,
   cwd: '.',
   env: process.env
});

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

nano.on('close', function () {
    process.exit();
});
Jason Livesay
  • 6,317
  • 3
  • 25
  • 31