简体   繁体   中英

how to start a text editor from node.js?

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.

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.

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM