如何发送控制 C node.js 和 child_processes

Yar*_* L. 5 windows child-process node.js

你好我要发送给child_process,比如ping 8.8.8.8-t,也就是无限次ping。有些迭代我想停止这个命令并执行一个新的,但在这种情况下我不想杀死一个子进程。

例子:

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');
Run Code Online (Sandbox Code Playgroud)

use*_*109 4

我找到了你之前的问题。看起来您正在尝试从 node.js 中创建/模拟终端。您可以使用readline从终端读取和写入。

要编写控制字符,您可以查看其文档中的示例:

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

要直接回答问题,要传递特殊字符,您需要传递它们的 ASCII 值。Ctrl+C变为 ASCII 字符 0x03。从这里获取的值。

  spawn.stdin.write("\x03");
Run Code Online (Sandbox Code Playgroud)