上下文
编写一个串行监视器来收听Arduino并不难。用端口名和波特率的命令行参数启动它很简单,因此从Node:配置和启动监视器并不复杂
child_process.exec("./monitor COM6 115200");
这个问题涉及exec
、fork
和spawn
,它们很相似,但有一些微妙之处,我还没有掌握。除了发射参数,我需要
- 捕获输出以便在窗口中显示
- 终止子进程
- 使用不同参数重新启动
- 刷新Arduino,然后在重新启动后重新启动
我使用netcore编写了一个控制台应用程序,该应用程序接受两个命令行参数,然后连接并侦听,并返回到其stdout
。我选择netcore是因为它可以在所有三个平台上运行。
问题
我应该使用exec
、fork
和spawn
中的哪一个?
如何终止子进程?
如何捕获子进程的stdout
?
节点文档讨论了subprocess
对象上的kill方法。该页面上的示例代码暗示这个对象是由spawn
返回的,但当我使用spawn时,它似乎会无声地失败。这或它正在起作用,但我不知道我在做什么,这就是我提出这个问题的原因。
所有这些Node代码都将是VSCode扩展的一部分,所以如果你也知道这些,如果可能的话,我想将stdout管道传输到VSCode OutputChannel。
使用spawn,您可以监听stdout。
然后用kill((终止进程
来自官方NodeJS文档:
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
// some logic
ls.kill()
EDIT:一个更具体的例子:
// server.js --------------
const http = require('http');
const server = http.createServer(
(function() {
console.log('Initializing server');
return (req, res) => {
res.end('Hello World');
};
})()
);
server.listen(8080, () => console.log('Server is up on port ' + 8080));
// spawn.js --------------
const { spawn } = require('child_process');
const child = spawn('node', ['./server.js']);
child.stdout.on('data', data => console.log(data.toString()));
child.stderr.on('data', data => console.log('Error: ' + data));
child.on('close', code => console.log(`Process ended with code ${code}`));
child.on('error', err => console.log(err));
setTimeout(() => child.kill(), 2000);