Question

I am trying to understand the purpose of addListener in node.js. Can someone explain please? Thanks! A simple example would be:

var tcp = require('tcp');
var server = tcp.createServer(function (socket) {
  socket.setEncoding("utf8");
  socket.addListener("connect", function () {
    socket.write("hello\r\n");
  });
  socket.addListener("data", function (data) {
    socket.write(data);
  });
  socket.addListener("end", function () {
    socket.write("goodbye\r\n");
    socket.end();
  });
});
server.listen(7000, "localhost");
Was it helpful?

Solution

Due to the fact that Node.js works event-driven and executes an event-loop, registering listeners allow you to define callbacks that will be executed every time the event is fired. Thus, it is also a form of async. code structuring.

It's comparable to GUI listener, that fire on user interaction. Like a mouse click, that triggers an execution of code in your GUI app, your listeners in your example will be run as soon as the event happens, i.e. a new client connects to the socket.

OTHER TIPS

it registers a listener for an "event". Events are identified by strings, such as "connect" and "data". the second argument is a function, a so called "callback", also refered to as "event handler". Whenever a specific event occurs within the object the listeners have been registered to, all handlers are invoked.

node.js uses this, because it employs an asynchronous execution model, that can best be handled with an event-driven approach.

greetz
back2dos

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top