How to send control C node.js and child_processes
Asked Answered
K

1

6

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');
Kirsch answered 15/7, 2013 at 7:16 Comment(0)
A
4

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");
Aileen answered 15/7, 2013 at 15:30 Comment(2)
Sorry, but I do not really understand how I use it as a terminal and send, such as ping. Maybe tell me? spawn.stdin.write("\x03") - not working :(Kirsch
Not working for me as well, even setting ascii mode self.child.stdin.setEncoding('ascii'); self.child.stdin.write("\x03");//CTRL-CTobacco

© 2022 - 2024 — McMap. All rights reserved.