Backend Event Handling with Node.js

Published on
Embed video
Share video
Ask about this video

Scene 1 (0s)

[Audio] Good day, class! For our discussion, we will focus on Backend Event Handling with Node.js, which is an important topic under Event-Driven Programming. In our previous discussions, we explored how event-driven programming allows applications to respond to different events or actions rather than simply executing instructions sequentially. Today, we will extend that understanding to the backend side of application development. When we use a web application, we normally see the interface, buttons, forms, and other visual elements. However, behind that interface, there is a backend system responsible for processing requests, communicating with databases, managing information, and sending responses to users. This is where Node.js becomes important. We will understand how Node.js works, how it handles multiple users simultaneously, and why developers use it to build modern applications such as chat systems, Internet of Things platforms, human resource information systems, and other web-based solutions..

Scene 2 (1m 9s)

[Audio] Before proceeding with the discussion, let us examine our learning objectives. At the end of this lesson, you should be able to define Node.js and explain its major characteristics, particularly its event-driven and non-blocking architecture. This means that you should understand why Node.js is different from traditional server-side technologies and how it manages multiple requests without unnecessarily waiting for one operation to finish before accepting another. You should also be able to explain the internal components responsible for processing requests, including the event loop, event queue, V8 engine, and libuv. Another important objective is applying Node.js concepts to actual systems, such as chat applications, IoT monitoring platforms, and HR information systems. Finally, you should be able to evaluate both the advantages and limitations of Node.js. Remember that learning a technology is not simply about memorizing its definition. As future IT professionals, you must understand when a technology is appropriate, how it works, and what problems it can solve..

Scene 3 (2m 23s)

[Audio] Let us begin by understanding what Node.js is. Node.js is a free and open-source runtime environment that allows developers to execute JavaScript outside a web browser. Normally, when we write JavaScript, we associate it with the browser because it is commonly used to make websites interactive. For example, when a user clicks a button, JavaScript can validate a form, display a message, or update a section of a webpage. However, JavaScript is not limited to browser-based activities. Through Node.js, developers can also use JavaScript to create applications that run on servers. This means that the same programming language used to develop interactive website interfaces can also be used to process backend operations. For example, imagine that you are developing an online enrollment system. The frontend allows students to enter their personal information, while the backend receives the information, validates it, and saves it to a database. Node.js can be used to develop that backend functionality. The video included in the presentation introduces Node.js and provides an overview of how it works. As you watch, pay attention to the difference between running JavaScript inside a browser and running JavaScript through the Node.js runtime..

Scene 4 (3m 49s)

[Audio] Node.js is a runtime environment that allows developers to build fast and scalable applications, including web servers, APIs, and other backend tools. Let us clarify two important applications mentioned in the presentation. First, we have web servers. A web server receives requests from users and sends the appropriate responses. For example, when you visit an online shopping website, your browser sends a request to the server to display the homepage. A Node.js server using Express.js can receive that request and deliver the necessary webpage or information. Second, we have APIs or Application Programming Interfaces. An API acts as a communication bridge between different applications. For instance, imagine that you have a mobile application for checking student grades. The mobile application needs to retrieve student records from the university database. Instead of directly accessing the database, the mobile application sends a request to a Node.js REST API. The API processes the request and returns the information, commonly in JSON format. This allows different applications to communicate even if they were developed using different technologies. The important concept here is that Node.js allows JavaScript to perform backend responsibilities, not just frontend interactions..

Scene 5 (5m 21s)

[Audio] Node.js is a versatile technology because it can be used to develop different types of applications. The first example is web servers and websites. Developers can use Node.js with Express.js to host websites, manage user requests, and provide application content. For example, a university website can use a Node.js backend to display announcements, student information, and course offerings. Another application is REST APIs, which allow frontend applications, mobile applications, and other systems to exchange information. Node.js is also useful for real-time applications such as chat systems. Consider Facebook Messenger or a university messaging platform. When one student sends a message, the system should immediately notify the recipient without requiring the recipient to refresh the page. Node.js can support this functionality through technologies such as Socket.io. Another application is command-line tools. These are programs that run through a terminal or command prompt. For example, developers can create a Node.js tool that automatically renames hundreds of files or organizes project folders. Node.js can also work with files and databases. An example is a document submission system where students upload requirements, and the backend saves the documents and stores their information in MySQL or MongoDB. Finally, Node.js can be used in IoT and hardware control. Through platforms such as Johnny-Five, developers can interact with sensors, lights, and other electronic devices. For example, a smart classroom system could use Node.js to receive temperature readings and control an electric fan automatically. These examples demonstrate that Node.js is not limited to ordinary website development. It can also support automation, communication, data management, and hardware integration..

Scene 6 (7m 32s)

[Audio] Now that we understand what Node.js can do, let us discuss how to execute a Node.js program. Unlike browser-based JavaScript, which is usually executed through a webpage, Node.js programs can be executed directly through the terminal or command prompt. First, a developer must install Node.js on the computer. After installation, the developer can check whether Node.js is available by typing node -v in the terminal. This command displays the installed Node.js version. Next, create a JavaScript file, for example, app.js, and write a simple instruction such as console.log("Hello, Node.js!");. Save the file and open the terminal in the same directory where the file is located. Type node app.js and press Enter. Node.js will execute the JavaScript code and display the message in the terminal. Notice that there is no need to open a browser or create an HTML webpage. This is because Node.js itself provides the environment needed to execute JavaScript. As a practical example, developers can use this approach to test backend logic, create automation scripts, and develop server applications. It is important to remember that the filename can be different; it does not need to be named node.js. What matters is that the command references the correct JavaScript filename..

Scene 7 (9m 8s)

[Audio] To understand why Node.js became popular, let us look at its history. Node.js was created by Ryan Dahl in 2009. At that time, one of the challenges in web server development was how to efficiently handle multiple requests, especially when operations involved reading files, accessing databases, or communicating through networks. Traditional blocking approaches could cause a server thread to wait until a particular operation was completed. If many users requested information simultaneously, the server could experience delays. Ryan Dahl introduced Node.js with an event-driven and non-blocking approach to address this challenge. Another important component of Node.js is Google's V8 JavaScript engine, which executes JavaScript efficiently. By combining JavaScript with non-blocking input/output operations, Node.js became suitable for applications that need to manage many simultaneous connections. Over time, it became widely adopted for real-time applications, APIs, and microservices. The presentation also identifies the OpenJS Foundation as the organization responsible for its maintenance and governance. Today, Node.js is used in different environments, from small startup projects to large enterprise applications. Its development demonstrates how an existing programming language can evolve beyond its original browser-based purpose..

Scene 8 (10m 43s)

[Audio] Although Node.js and web browsers both execute JavaScript, they operate in different environments and have different responsibilities. Let us begin with Node.js. Node.js is primarily designed for server-side development. This means that it is commonly used to process requests, manage application logic, access files, and communicate with databases. On the other hand, a browser is designed to run client-side applications. It displays webpages and provides the environment where users interact with buttons, forms, images, and other interface components. One major difference is the availability of system-level APIs. Node.js provides access to file system operations through its built-in modules, while browsers restrict direct access to local files for security reasons. For example, a Node.js application can read a text file stored on the server using the File System module. A browser-based application cannot freely read any file from a user's computer without permission or an approved user interaction. Another difference is the availability of the Document Object Model or DOM. Browsers provide the DOM, which allows JavaScript to manipulate webpage elements. Node.js does not provide a browser DOM by default because it is not designed to display webpages. Therefore, remember this distinction: Node.js primarily handles backend operations, while browsers primarily handle the user-facing interface..

Scene 9 (12m 24s)

[Audio] In Node.js, the global object is called global, while browsers traditionally use window or self. A global object provides access to values and functions that are available throughout a particular JavaScript environment. For example, in Node.js, developers can use global to define a property that can be accessed by different parts of an application. However, for code that needs to work in both environments, JavaScript provides globalThis, which refers to the global object in either environment. The second difference is file system access. Node.js provides built-in functionality for reading, writing, and managing files, while browsers operate within a security sandbox. This prevents websites from freely accessing a user's private files. Third, both environments use an event loop, but Node.js provides additional runtime APIs for operations involving timers, processes, and server-side networking. Finally, Node.js commonly uses package managers such as npm and Yarn to install and manage external libraries. Browser applications may also use npm and bundlers during development, or load selected libraries through content delivery networks or CDNs. The important lesson is that although both environments use JavaScript, their available features depend on where the code executes..

Scene 10 (13m 56s)

[Audio] In Node.js, we can use global, while in a browser we can use window. For example, consider a JavaScript instruction that accesses a property called appName. In a Node.js environment, a developer may define global.appName = "Student System"; and then access that property through the global object. In a browser, a similar example would be window.appName = "Student System";. However, if the same code needs to work in both environments, developers can use globalThis.appName = "Student System";. This is particularly useful when creating reusable JavaScript libraries that may run in different environments. Let us relate this to a real-world situation. Suppose a developer is building a JavaScript utility that will be used by both a Node.js backend and a browser-based frontend. Using globalThis can help avoid environment-specific references when accessing the global object. The key takeaway is that JavaScript does not always use the same global object name in every environment. Developers must understand the environment in which their code will execute..

Scene 11 (15m 13s)

[Audio] Node.js provides a built-in module called fs, which stands for File System. This module allows developers to perform operations such as reading, writing, deleting, and renaming files. For example, imagine that a university has a document management system where instructors upload examination files and learning materials. The Node.js backend can receive the uploaded files, save them in an appropriate server directory, and record their filenames in a database. Developers can also use the fs module to read configuration files when an application starts. In contrast, browsers do not allow JavaScript to freely access files stored on a user's computer. Imagine visiting an unknown website. If that website could automatically read every document on your computer, your privacy and security would be at risk. This is why browser environments restrict direct file system access. However, browsers can still allow users to select files through file input elements and can provide controlled file access through approved browser APIs. The important distinction is that Node.js is designed for server-side file operations, while browser file access is restricted to protect users..

Scene 12 (16m 33s)

[Audio] In Node.js, developers can use built-in modules such as http and https to create servers or make HTTP requests. These modules provide functionality for handling network communication and processing response data. For example, suppose a Node.js application needs to retrieve information from an external government API. The application can send an HTTPS request, receive the response, and process the returned information. The presentation highlights how Node.js can handle response data in chunks. This is useful when working with large amounts of data because the application does not always need to wait for the entire response before processing it. In a browser, developers commonly use the Fetch API. For example, a student portal can use fetch() to request the student's grades from a backend API and display the returned information on the webpage. The Fetch API uses Promises, making asynchronous network operations easier to manage. Both environments support network communication, but the available APIs and their intended purposes differ. Node.js provides more backend-oriented networking capabilities, while browsers provide convenient APIs for communication between webpages and servers..

Scene 13 (18m 1s)

[Audio] Node.js architecture. Architecture refers to the overall structure and organization of a system, including how its components work together to perform specific tasks. Node.js uses a single-threaded, event-driven architecture designed to handle multiple connections efficiently. When we say single-threaded, we mean that JavaScript application code normally executes on one main thread. This is different from traditional server designs that may assign a separate thread to every incoming client request. However, single-threaded does not mean that Node.js can only perform one operation at a time. Through asynchronous programming and non-blocking I/O, it can initiate operations and continue processing other events while waiting for those operations to finish. For example, imagine that 100 students access an online enrollment system at the same time. Some students may be retrieving information, others may be submitting forms, and others may be checking their enrollment status. Node.js can initiate the required operations without keeping the main JavaScript thread waiting for every database or network operation to complete. This architecture makes Node.js particularly useful for network applications, real-time systems, and APIs. However, developers must avoid placing long-running CPU-intensive tasks directly on the main event loop because these can delay the processing of other requests..

Scene 14 (19m 33s)

[Audio] Let us examine how Node.js manages multiple incoming requests. Imagine that several users access the same website at the same time. The Node.js server receives these requests and processes their associated events through its event loop. The event loop determines which operations can be handled immediately and which operations require asynchronous processing. For example, displaying a simple response may require very little processing, while reading a large file or performing a network operation may take longer. For operations that involve waiting, Node.js can delegate the work to the operating system or to libuv's worker thread pool, depending on the type of operation. The important point is that the main JavaScript thread does not need to remain idle while waiting for these operations. It can continue processing other incoming requests. Once an asynchronous operation is completed, its completion event is made available for processing, and the corresponding callback or Promise continuation is executed. Consider an online shopping application. One customer is checking product information, another is submitting an order, and another is retrieving an invoice. While the server waits for a database or file operation, it can continue accepting and processing other requests. This is how Node.js supports concurrent connections efficiently. The slide simplifies the internal process by referring to asynchronous threads. In practice, the operating system and libuv handle different categories of I/O operations through different mechanisms..

Scene 15 (21m 14s)

[Audio] Let us examine each component. First, we have the application, which refers to the JavaScript code written by the developer. This may contain instructions for creating a server, receiving requests, and accessing databases. Second, we have the V8 engine. V8 is the JavaScript engine developed by Google and used by Node.js to execute JavaScript code efficiently. It compiles and optimizes JavaScript for execution. Third, we have Node.js bindings. These act as a connection between JavaScript and lower-level functionality implemented in native code. They allow JavaScript applications to access operating-system-related features. Fourth, we have libuv, which is an important library responsible for asynchronous I/O operations, the event loop, and the worker thread pool. The event queue or related internal queues hold callbacks and other work that is ready to be processed. The event loop continuously checks the appropriate queues and schedules callbacks for execution. The worker thread pool handles certain operations that should not block the main JavaScript thread, such as some file system operations and other supported tasks. Let us use a practical example. Suppose a user requests a report from a Node.js application. The JavaScript application receives the request, the server initiates the necessary database or file operations, and the asynchronous operation is handled through the appropriate runtime mechanisms. Once the operation completes, the application receives the result and sends the report back to the user. These components work together to make Node.js efficient in handling asynchronous operations..

Scene 16 (23m 1s)

[Audio] A typical web application can be divided into three major components: the client, the server, and the database. These three components work together to provide the services that users access through a web browser or mobile application. The client represents the user-facing part of the application. It is where users enter information, click buttons, and view results. The server receives requests from the client, processes the required instructions, and communicates with the database when information needs to be stored or retrieved. The database stores the application's information, such as user accounts, student records, product information, and financial transactions. Let us use an online enrollment system as an example. When a student opens the enrollment webpage, the client displays the enrollment form. When the student submits the form, the server receives the submitted information, validates the data, and communicates with the database to save the enrollment record. After the database operation is completed, the server sends a response to the client, informing the student whether the submission was successful. This three-part structure helps developers separate responsibilities, making the application easier to maintain, develop, and improve..

Scene 17 (24m 18s)

[Audio] The client is the frontend component of a web application. It represents everything that users directly interact with, including webpages, buttons, navigation menus, forms, images, and other visual elements. The client is usually developed using HTML, CSS, and JavaScript. HTML provides the structure of the webpage. For example, it defines headings, paragraphs, tables, forms, and buttons. CSS controls the appearance of these elements, including their colors, spacing, fonts, and layout. JavaScript adds interactivity, allowing the webpage to respond to user actions. The presentation also mentions frontend frameworks such as ReactJS and Angular. These frameworks help developers build more organized and dynamic user interfaces. For example, imagine a student information system. The client displays the student's name, profile, enrolled subjects, and grades. When the student clicks the View Grades button, the frontend sends a request to the backend server. The server retrieves the grades from the database and sends them back to the client. The client then displays the results. It is important to understand that the client is responsible for presenting information and collecting user input, but important business rules and database operations should be handled securely by the backend..

Scene 18 (25m 47s)

[Audio] The server is the backend component responsible for receiving requests, processing information, and returning responses to clients. It serves as the communication bridge between the frontend and the application's resources, such as databases, file systems, and external APIs. In a Node.js application, the server can be developed using the Express.js framework, which simplifies the creation of routes and request handlers. For example, consider an online student registration system. When a student submits an enrollment form, the frontend sends an HTTP POST request to the server. The Node.js server receives the request, checks whether the required fields are complete, validates the information, and saves the record to the database. After the operation, the server sends a response to the frontend indicating whether the enrollment was successful. The presentation also mentions PHP and Java as other technologies used to develop servers. These are alternative backend technologies that can perform similar responsibilities. The choice of technology depends on the requirements of the project, the skills of the development team, and the expected system workload. What is important is understanding the server's role in connecting the user interface with the application's backend resources..

Scene 19 (27m 14s)

[Audio] The database is the component responsible for storing, organizing, managing, and retrieving application information. Almost every information system requires a database because applications need a reliable way to preserve data even after users close their browsers or log out. For example, an enrollment system stores student information, course offerings, subjects, and enrollment records. A payroll system stores employee profiles, salary information, attendance records, and payroll transactions. The presentation identifies MySQL and MongoDB as examples of databases commonly used with Node.js. MySQL is a relational database management system that organizes information into tables containing rows and columns. MongoDB is a NoSQL document-oriented database that stores information in flexible document structures. When a client sends a request, the server may perform one of the four basic database operations known as CRUD: Create, Read, Update, and Delete. For example, when a student creates an account, the system performs a Create operation. When the student views a profile, the system performs a Read operation. When the student changes an address, the system performs an Update operation. When an authorized administrator removes an obsolete record, the system performs a Delete operation. The database is therefore essential because it allows the application to maintain and manage information systematically..

Scene 20 (28m 52s)

[Audio] This introduces three major advantages of Node.js architecture: fast and efficient request handling, single-threaded architecture, and high performance and responsiveness. First, Node.js supports efficient request handling through its event-driven architecture and asynchronous operations. Consider a chat application where hundreds of users send messages simultaneously. Instead of requiring the main JavaScript thread to wait for each network operation, Node.js can manage the connections asynchronously. The second advantage is its single-threaded JavaScript execution model. This simplifies the way developers manage concurrent application logic because they do not normally need to create and synchronize a separate JavaScript thread for every request. The slide provides the analogy of a cashier who takes customer orders and passes them to the kitchen. The cashier does not personally prepare every meal. Instead, the cashier continues accepting orders while the kitchen prepares previous orders. Similarly, Node.js initiates operations and allows other components to perform the waiting or background work. The third advantage is high performance and responsiveness. For example, imagine a stock market application that displays continuously changing stock prices. Node.js can receive updates asynchronously and distribute the information to connected users. These characteristics make it useful for applications that require frequent communication and many simultaneous connections. However, remember that its performance depends on how the application is designed and whether its operations are suitable for non-blocking execution..

Scene 21 (30m 41s)

[Audio] This emphasizes three benefits of the event-driven, non-blocking I/O model: scalability, responsiveness, and resource efficiency. Let us first discuss scalability. Scalability refers to the ability of a system to accommodate an increasing number of users or requests without experiencing unacceptable performance problems. The presentation uses a live sports score application as an example. Imagine that thousands of people are checking the scores of a championship basketball game at the same time. The server must continuously receive requests and distribute updated information. Because Node.js uses non-blocking I/O, it can manage many concurrent connections without waiting for every individual operation to finish. Second is responsiveness. Consider a chat application. When a user sends a message, the server receives the message event and distributes it to the appropriate recipients. Through event-driven communication, users can receive updates quickly without continuously refreshing the webpage. Third is resource efficiency. Node.js avoids keeping the main JavaScript thread blocked while waiting for supported I/O operations. For example, if a server is processing a file upload, it can continue handling other incoming requests while the file operation is being completed. This improves the utilization of system resources. However, the main thread can still become blocked by CPU-intensive JavaScript operations, so developers must design their applications carefully..

Scene 22 (32m 21s)

[Audio] Now let us connect Node.js with the central concept of our subject, Event-Driven Programming. An event-driven model is a programming approach where the application responds to events rather than simply executing every instruction in a fixed sequence. An event may come from a user action, a network request, a completed file operation, a timer, or another application component. The presentation gives an analogy of a waiter in a restaurant. A waiter does not prepare the food personally. Instead, the waiter responds when a customer places an order, communicates that order to the kitchen, and returns when the food is ready. This is similar to event-driven programming. The system waits for events and executes the appropriate response when an event occurs. In Node.js, the event loop plays a central role in this process. It continuously checks for work that is ready to be processed and executes the corresponding callback functions. Another important concept is the callback mechanism. A callback is a function passed to another function so that it can be executed later, usually when a particular operation or event has completed. For example, suppose a Node.js application reads a student record from a file. The application initiates the file-reading operation and provides a callback. Once the operation completes, the callback receives the result and processes the information. This allows the application to perform other tasks while waiting for the file operation. This is the foundation of event-driven and asynchronous programming in Node.js..

Scene 23 (34m 6s)

[Audio] One of the most important characteristics of Node.js is non-blocking input/output or I/O. To understand this, we must first understand what blocking means. In traditional blocking I/O, when a program requests information from a file or external system, the program waits until that operation finishes before proceeding with the next instruction. For example, imagine an application that needs to read a large file. If the operation blocks the main execution thread, other tasks that depend on that thread may be delayed. This can become a problem when a server receives requests from many users. Node.js addresses this through non-blocking I/O. Instead of waiting for an operation to finish, Node.js initiates the operation and continues executing other available tasks. When the operation is completed, the corresponding callback or Promise continuation is executed to handle the result. Let us consider a university system. Student A requests a transcript of records, Student B checks an enrollment status, and Student C uploads a document. While the system is waiting for a file or database operation related to Student A, it can continue processing other requests. This improves the responsiveness of the application. Remember that non-blocking does not mean that the operation finishes instantly. It means that the main execution thread is not unnecessarily held up while waiting for that operation. This is one of the main reasons Node.js is useful for applications with many concurrent network connections..