Day 10 of 100days of code.

Day 10 of 100days of code.

Β·

3 min read

My transition into backend development stems from a desire to craft end-to-end solutions that seamlessly integrate frontend interfaces with backend architectures. Lets GooooπŸ’ͺπŸΌπŸš€

Fundamentals of nodeJS

Understanding event-driven architecture

in an event driven architecture we have three main players

  • Event Emitter

  • Event Listener

  • Event Handler

An Event Emitter emits named events when something important happens in the app. For example a request hitting the server, a timer expiring or a file finishing to read all of these emit events. When an event is emitted or raised, the event can be picked up by an Event Listener. The Event Listener wait for an event to happen then fire up a call back function attached to that event listener when the event happens. The call back function is called Event Handler.

When we want to create a server, we use the createServer() method on the HTTP object and then assign it to a variable called server. Whenever a new request hits the server, the server will emit a named event called request. request is the named event and the server is the emitter because the serve emits the request event. When the named event is emitted we can listen to the named event using an event listener.

Lets update our code base from previous lessons

For more clarity, Lets create a new variable server and assign the createServer() method. i.e : const server = http.createServer()

Whenever a new request hits the server, the server object will emit a request event and we can listen to the event using the on() method. The on() method takes two arguments. For the first argument we need to specify the event we want to listen and for the second argument we pass the event listener which is a call back function which will be executed whenever the event happens. The call back function will also receive some arguments. So basically when the server raises the request event, with the request event it will also pass the req and res objects to the event handler function. i.e: server.on("request", (req, res) =>{}).

For the first server variable we created, lets copy the logic we wrote inside the call back function and paste inside the call back function of our on() method and afterwards we remove or comment out the previous server variable code block. πŸ‘‡πŸΌ

Our previous server variable code block. πŸ‘‡πŸΌ

lets restart the server and check if our application is still working.

Still working perfectly. πŸ‘‡πŸΌ

So instead of passing a call back function to the createServer() method, we are listening to the request event whenever a new request hits the server using the on() method.

Next: Emitting and handling.

See you soon😊🫑✌🏼...

Β