Node.js Events

Tutorial Difficulty Level    

Every action on a computer is an event. Like when a connection is made or a file is opened, for example. Node.js is perfect for event-driven applications because objects in Node.js can fire events, like the readStream object fires events when opening and closing a file.

Node.js has a built-in module, called “Events”, where you can create-, fire-, and listen for- your own events.

To include the built-in Events module use the require() method. In addition, all event properties and methods are an instance of an EventEmitter object. To be able to access these properties and methods, create an EventEmitter object:

You can also assign event handlers to your own events with the EventEmitter object.

In the example below we have created a function that will be executed when a “scream” event is fired.

To fire an event, use the emit() method.