How to send control C node.js and child_processes

一笑奈何 提交于 2019-12-24 01:48:09

问题


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');

回答1:


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");


来源:https://stackoverflow.com/questions/17648654/how-to-send-control-c-node-js-and-child-processes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!