Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does addListener do in node.js?

I am trying to understand the purpose of addListener in node.js. Can someone explain please? 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");
like image 400
Jeff Avatar asked Apr 29 '10 11:04

Jeff


1 Answers

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.

like image 168
b_erb Avatar answered Oct 06 '22 19:10

b_erb