Events in Node.js

Since Javascript is an event driven language, many objects in Node.js emit events. Events are the important things that make Node.js awesome. There are tons of objects that emit events in node. You can find several examples in the documentation. To access events you need to use require("events"). I’ve written a sample application that demonstrates how to add listeners and bind to events. I’ve added several comments throughout the code so feel free to ask any questions in the comments below.


// Include the necessary modules.
var net = require('net');
var events = require("events");  

// Required.  Creates an instance of EventEmitter
var channel = new events.EventEmitter();

// Since channel is an instance of EventEmitter, we will
// be using this to listen to events.  Here we add a listener
// for "message" event.  This will be called each time the
// "message" event is fired.
channel.addListener('message', function (msg) {
   console.log('Message: ' + msg.text);

// Create an instance of server
var server = net.createServer(function(socket) {
    var id = socket.remoteAddress + ":" + socket.remotePort;
    // Bind to the "connect" event.  This is the event that gets emitted when a connection is made.
    socket.on('connect', function() {
        channel.emit('message', {text: "Client connected: " + id});
    // Bind to the "close" event.  This is the event that gets emitted when a connection is closed.
    socket.on('close', function() {
        channel.emit('message', {text: 'Client disconnected: ' + id});
        channel.emit('shutdown');  //fire the "shutdown event
    // Bind to the "data" event.  This is the event that gets emitted when data is available (body/header).
    socket.on('data', function(data) {
        channel.emit('message', {text: data});

// Bind to the "shutdown" event.
channel.on('shutdown', function () {
    this.removeAllListeners();  // removes all listeners
    console.log('Channel shutting down');

console.log('Server Running...')

You can run this with:

node server.js

Navigate to localhost:8888. You should see the events being logged in terminal. Try closing the window and you should see the shutdown event being emitted.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please Do the Math