Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send control C node.js and child_processes

Hello I want to send to the child_process, for example, ping 8.8.8.8-t, that is, an infinite number of ping. And some of the iterations I want to stop this command and execute a new, but in this case I do not want to kill a child process.

Example:

var spawn = require('child_process').spawn('cmd'),
    iconv = require('iconv-lite');

spawn.stdout.on('data', function (data) {
    console.log('Stdout: ', iconv.decode(data, 'cp866'));
});

spawn.stderr.on('data', function (data) {
    console.log('Stderr: ', iconv.decode(data, 'cp866'));
});

spawn.stdin.write('ping 8.8.8.8 -t'+ '\r\n');

spawn.stdin.write(here control-c...); // WRONG

spawn.stdin.write('dir' + '\r\n');
like image 951
Yaroslav L. Avatar asked Oct 22 '22 05:10

Yaroslav L.


1 Answers

I found your previous question. Looks like you are trying to create/emulate a terminal from within node.js. You can use readline for reading and writing from a terminal.

To write control character, you can see the example from its docs :

  rl.write('Delete me!');
  // Simulate ctrl+u to delete the line written previously
  rl.write(null, {ctrl: true, name: 'u'});

To directly answer the question, to pass special characters you will need to pass their ASCII values. Ctrl + C becomes ASCII character 0x03. Value taken from here.

  spawn.stdin.write("\x03");
like image 102
user568109 Avatar answered Oct 27 '22 11:10

user568109