Nodejs events

From wikinotes
Revision as of 23:20, 4 July 2021 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Documentation

api docs https://nodejs.org/api/events.html

Basics

const Event = require('events');

// define event, and subscribers
const event = new Event()
event.on('start', () => { console.log('hi') })

// emit to event
event.emit('start')

You can also emit params.

event.emit('start', 1, 2, 3)

Listeners

const Event = require('events');

// define event 
const event = new Event()

// append listeners
event.on('start', () => { ... })   // listen to all events
event.once('start', () => { ... }) // listen to first event only

// prepend listeners
event.prependListener('start', () => { ... })  // add to top of array of listeners
event.prependOnceListener('start', () => { ... })  // add to top of array of listeners

Errors

By convention, event errors are emitted to "error".

const error = new Error('there was an error');
event.on('error', (error) => { console.log('there was an error') });

Asynchronous Execution

Events execute synchronously in the order they were enqueued.
You can make them async using timers.

event.on('start', setTimer(() => { console.log('foo') }, 0))