简体   繁体   English

Node js子进程事件发射器与回调

[英]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 attach multiple listeners to the same event.您可以将多个侦听器附加到同一事件。 Callbacks are one-to-one notifications, events - one-to-many.回调是一对一的通知,事件 - 一对多。
  • You can't return value from the event.您不能从事件中返回值。 Events are one-way messages.事件是单向消息。 Often, callbacks follow (error, data1, data2, data3, ...) signature because a single callback responsible for normal and error data flow (and async libraries usually expect this behaviour)通常,回调遵循 (error, data1, data2, data3, ...) 签名,因为单个回调负责正常和错误数据流(并且异步库通常期望这种行为)
  • EventEmitter-based API, on the other hand, tend to separate error and non-error messages另一方面,基于 EventEmitter 的 API 倾向于区分错误和非错误消息
  • "error" event is special in event emitter: if there is no listener for it, EventEmitter throws an exception. “error”事件在事件发射器中是特殊的:如果没有监听器,EventEmitter 会抛出异常。 With callbacks, it's your responsibility to check the first error parameter.使用回调,检查第一个错误参数是您的责任。

You can check this link on stackoverflow for difference b/w callback and events.您可以在 stackoverflow 上查看链接,了解不同的黑白回调和事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM