Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
If you worked with JavaScript in the browser, you know how much of the interaction of the user is handled through events: mouse clicks, keyboard button presses, reacting to mouse movements, and so on.
On the backend side, Node offers us the option to build a similar system using the events
module.
This module, in particular, offers the EventEmitter
class, which we’ll use to handle our events.
You initialize an EventEmitter object using this syntax:
const EventEmitter = require('events')
const eventEmitter = new EventEmitter()
This object exposes, among many others, the on
and emit
methods.
emit
is used to trigger an eventon
is used to add a callback function that’s going to be executed when the event is triggered
Emit and listen for events
For example, let’s create a start
event, and as a matter of providing a sample, we react to that by just logging to the console:
eventEmitter.on('start', () => {
console.log('started')
})
When we run
eventEmitter.emit('start')
the event handler function is triggered, and we get the console log.
addListener()
is an alias for on()
, in case you see that used.
Passing arguments to the event
You can pass arguments to the event handler by passing them as additional arguments to emit()
:
eventEmitter.on('start', (number) => {
console.log(`started ${number}`)
})
eventEmitter.emit('start', 23)
Multiple arguments:
eventEmitter.on('start', (start, end) => {
console.log(`started from ${start} to ${end}`)
})
eventEmitter.emit('start', 1, 100)
Listen for an event just once
The EventEmitter object also exposes the once()
method, which you can use to create a one-time event listener.
Once that event is fired, the listener stops listening.
Example:
eventEmitter.once('start', () => {
console.log(`started!`)
})
eventEmitter.emit('start')
eventEmitter.emit('start') //not going to fire
Removing an event listener
Once you create an event listener, you can remove it using the removeListener()
method.
To do so, we must first have a reference to the callback function of on
.
In this example:
eventEmitter.on('start', () => {
console.log('started')
})
Extract the callback:
const callback = () => {
console.log('started')
}
eventEmitter.on('start', callback)
So that later you can call
eventEmitter.removeListener('start', callback)
You can also remove all listeners at once on an event, using:
eventEmitter.removeAllListeners('start')
Getting the events registered
The eventNames()
method, called on an EventEmitter object instance, returns an array of strings that represent the events registered on the current EventListener:
const EventEmitter = require('events')
const eventEmitter = new EventEmitter()
eventEmitter.on('start', () => {
console.log('started')
})
eventEmitter.eventNames() // [ 'start' ]
listenerCount()
returns the count of listeners of the event passed as parameter:
eventEmitter.listenerCount('start') //1
Adding more listeners before/after other ones
If you have multiple listeners, the order of them might be important.
An EventEmitter object instance offers some methods to work with order.
emitter.prependListener()
When you add a listener using on
or addListener
, it’s added last in the queue of listeners, and called last. Using prependListener
it’s added, and called, before other listeners.
emitter.prependOnceListener()
When you add a listener using once
, it’s added last in the queue of listeners, and called last. Using prependOnceListener
it’s added, and called, before other listeners.
Download my free Node.js Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More node tutorials:
- An introduction to the npm package manager
- Introduction to Node.js
- HTTP requests using Axios
- Where to host a Node.js app
- Interact with the Google Analytics API using Node.js
- The npx Node Package Runner
- The package.json guide
- Where does npm install the packages?
- How to update Node.js
- How to use or execute a package installed using npm
- The package-lock.json file
- Semantic Versioning using npm
- Should you commit the node_modules folder to Git?
- Update all the Node dependencies to their latest version
- Parsing JSON with Node.js
- Find the installed version of an npm package
- Node.js Streams
- Install an older version of an npm package
- Get the current folder in Node
- How to log an object in Node
- Expose functionality from a Node file using exports
- Differences between Node and the Browser
- Make an HTTP POST request using Node
- Get HTTP request body data using Node
- Node Buffers
- A brief history of Node.js
- How to install Node.js
- How much JavaScript do you need to know to use Node?
- How to use the Node.js REPL
- Node, accept arguments from the command line
- Output to the command line using Node
- Accept input from the command line in Node
- Uninstalling npm packages with `npm uninstall`
- npm global or local packages
- npm dependencies and devDependencies
- The Node.js Event Loop
- Understanding process.nextTick()
- Understanding setImmediate()
- The Node Event emitter
- Build an HTTP Server
- Making HTTP requests with Node
- The Node fs module
- HTTP requests in Node using Axios
- Reading files with Node
- Node File Paths
- Writing files with Node
- Node file stats
- Working with file descriptors in Node
- Working with folders in Node
- The Node path module
- The Node http module
- Using WebSockets with Node.js
- The basics of working with MySQL and Node
- Error handling in Node.js
- The Pug Guide
- How to read environment variables from Node.js
- How to exit from a Node.js program
- The Node os module
- The Node events module
- Node, the difference between development and production
- How to check if a file exists in Node.js
- How to create an empty file in Node.js
- How to remove a file with Node.js
- How to get the last updated date of a file using Node.js
- How to determine if a date is today in JavaScript
- How to write a JSON object to file in Node.js
- Why should you use Node.js in your next project?
- Run a web server from any folder
- How to use MongoDB with Node.js
- Use the Chrome DevTools to debug a Node.js app
- What is pnpm?
- The Node.js Runtime v8 options list
- How to fix the "Missing write access" error when using npm
- How to enable ES Modules in Node.js
- How to spawn a child process with Node.js
- How to get both parsed body and raw body in Express
- How to handle file uploads in Node.js
- What are peer dependencies in a Node module?
- How to write a CSV file with Node.js
- How to read a CSV file with Node.js
- The Node Core Modules
- Incrementing multiple folders numbers at once using Node.js
- How to print a canvas to a data URL
- How to create and save an image with Node.js and Canvas
- How to download an image using Node.js
- How to mass rename files in Node.js
- How to get the names of all the files in a folder in Node
- How to use promises and await with Node.js callback-based functions
- How to test an npm package locally
- How to check the current Node.js version at runtime
- How to use Sequelize to interact with PostgreSQL
- Serve an HTML page using Node.js
- How to solve the `util.pump is not a function` error in Node.js