[英]Node js Child process event emitter vs callbacks
Is there any difference between attaching callbacks or event listeners for child process in nodejs.在nodejs中为子进程附加回调或事件侦听器有什么区别。 like -
喜欢 -
const execute = require('child-process').exec;
const process = execute('ping -n 1 www.google.com'); // or ping -c 1 www.google.com for mac
process.stdout.on('data', data => {
console.log(data)
})
In the above code, I am using an event listener for the output and I am getting stdout data in windows but can't get the output in macOS.在上面的代码中,我使用了 output 的事件侦听器,我在 windows 中获取标准输出数据,但在 macOS 中无法获取 output。 But if I use callback like -
但是,如果我使用像这样的回调 -
const execute = require('child-process').exec;
execute('ping -c 1 www.google.com', (error, stdout, stderr) => {
console.log(stdout);
})
I am getting the output data in both windows and mac.我在 windows 和 mac 中都获得了 output 数据。 Is there any difference using callback or event listeners(both are asynchronous)?
使用回调或事件侦听器(两者都是异步的)有什么区别吗?
The callback
is called when the execution of that async task is completed.当该异步任务的执行完成时
callback
。 However, the events have to be fired based on the observer.但是,必须根据观察者触发事件。 Every event has listeners and when an event is fired its related listener function starts the executions.
每个事件都有监听器,当一个事件被触发时,它的相关监听器 function 开始执行。
You can check this link on stackoverflow for difference b/w callback and events.您可以在 stackoverflow 上查看此链接,了解不同的黑白回调和事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.