This content originally appeared on DEV Community and was authored by Eric Chapman
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')
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)
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')
})
Conclusion
That's it for today. Tomorrow the journey continue. Stay tune!
Follow me on Twitter: Follow @justericchapman
This content originally appeared on DEV Community and was authored by Eric Chapman
Eric Chapman | Sciencx (2021-04-07T14:09:35+00:00) Node.js 101 – Events. Retrieved from https://www.scien.cx/2021/04/07/node-js-101-events/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.