Node.js 101 - Events
source link: https://dev.to/ericchapman/node-js-101-events-5bmo
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK