Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Node.js, what's "on"?

In official doc, there is some sample code:

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

I can understand it except one part: what's on in res.on? What's the difference between it and addListener?

like image 538
Lai Yu-Hsuan Avatar asked Nov 26 '11 22:11

Lai Yu-Hsuan


People also ask

What is on () in node JS?

In Node. js, you usually bind functions (using 'on' or other functions) to listen to events.

What is tick in Nodejs?

When in Node JS, one iteration of the event loop is completed. This is known as a tick. process. nextTick() taking a callback function which is executed after completing the current iteration/tick of the event loop. Phases of Event Loop in Node JS from nodejs.org.

What is setImmediate in node JS?

The setImmediate function is used to execute a function right after the current event loop finishes. In simple terms, the function functionToExecute is called after all the statements in the script are executed. It is the same as calling the setTimeout function with zero delays.

What is Libuv in Nodejs?

libuv is a multi-platform C library that provides support for asynchronous I/O based on event loops. It supports epoll(4) , kqueue(2) , Windows IOCP, and Solaris event ports. It is primarily designed for use in Node. js but it is also used by other software projects.


2 Answers

As far as I'm aware, it's no different than addListener. There is some documentation on the event here: http://nodejs.org/docs/latest/api/events.html#emitter.on Both on and addListener are documented under the same heading. They have the same effect;

server.on('connection', function(stream) {
    console.log('someone connected!');
});

server.addListener('connection', function(stream) {
    console.log('someone connected!');
});
like image 59
Cody Avatar answered Sep 23 '22 05:09

Cody


Both on and addListener are aliases for the same function.

like image 33
Andrew Marsh Avatar answered Sep 21 '22 05:09

Andrew Marsh