In node.js “request.on” what is it this “.on”

前端 未结 3 643
抹茶落季
抹茶落季 2020-12-24 07:40

I\'m new in node.js and java script, i cant find meaning of this \".on\" keyword. when i change it with another word code failed.

var req = http.get(\"http:/         


        
相关标签:
3条回答
  • 2020-12-24 07:54

    The on method binds an event to a object.

    It is a way to express your intent if there is something happening (data sent or error in your case) , then execute the function added as a parameter. This style of programming is called Event-driven programming. You might want to look it up in the Wikipedia

    In node.js, there is a class called EventEmitter that provides you with all the code that you need for basic events if you decide to use them in your own code (which I would strongly recommend in the case of node.js). Docs for node.js EventEmitter are here

    0 讨论(0)
  • 2020-12-24 07:54

    The callback for http.get is invoked with a single argument (which you've named req). req, short for "request", is a common name, because this argument is an http.ClientRequest object. The http.ClientRequest object implements stream.Writable, and here's the important bit: all streams are instances of EventEmitter.

    EventEmitter has a function called on, which adds a listener function for a specified event.

    "listener function" is just another name for "callback function"

    In your example, you've added a listener for the data event and the error event. Listener functions are called (ergo the term "callback") by the EventEmitter.

    Extra Credit

    If you ever need a listener to stop listening (i.e., you no longer want your callback to be called), you can remove a listener with the emitter.removeListener function:

    var myCallback = function(e) { console.log('Got error: ' + e.message); }
    res.on('error', myCallback);
    // do some things...
    res.removeListener('error', myCallback);
    

    If you only want a listener to run once, you can use emitter.once instead of the on function, and then you won't have to remove it:

    res.once('error', myCallback);
    
    0 讨论(0)
  • 2020-12-24 08:14

    .on is a method use to bind event handler.

    0 讨论(0)
提交回复
热议问题