DEV Community

loading...
Cover image for Node.js 101 - Events

Node.js 101 - Events

ericchapman profile image Eric Chapman ・2 min read

Node.js Events

Much of the Node.js core is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") emit named events that cause Function objects ("listeners") to be called.

The following example shows a simple EventEmitter with a single listener that occur when for example a sale is made

const EventEmitter = require('events');

const myEmitter = new EventEmitter()

myEmitter.on('newSale', () => {
  console.log('A new sale occur')
})

myEmitter.emit('newSale')
Enter fullscreen mode Exit fullscreen mode

The eventEmitter.on() method is used to register listeners, while the eventEmitter.emit() method is used to trigger the event.

Passing arguments to listeners

The eventEmitter.emit() method allows an arbitrary set of arguments to be passed to the listener functions

const EventEmitter = require('events');

const myEmitter = new EventEmitter()

myEmitter.on('newSale', (total) => {
  console.log(`A new sale occur total of: ${price}`)
})

myEmitter.emit('newSale', 599.99)
Enter fullscreen mode Exit fullscreen mode

Node.j server work with eventEmitter

Now that we know about Node.js events. We are able to better understand the logic of the Node.js server object.

const server = http.createServer()

// this will create a event name request
server.on('request', (req, res) => {
  // when Node.js server trigger a request event this message will display
  res.end('Request received')
})

// this will loop and wait for events
server.listen(5000, '127.0.0.1', () => {
  console.log('Waiting for request')
})
Enter fullscreen mode Exit fullscreen mode

Conclusion

That's it for today. Tomorrow the journey continue. Stay tune!

Follow me on Twitter:

Discussion (0)

pic
Editor guide