NodeJS
Presented by:
Eng/ Ahmed Reda
What’s [Link]
[Link] is an open-source, cross-platform JavaScript runtime
environment that allows developers to execute JavaScript code
outside of a web browser
It is built on Chrome's V8 JavaScript engine, which compiles
JavaScript directly to native machine code for high
performance
[Link] enables developers to use JavaScript for server-side
scripting, making it possible to build scalable and high-
performance network applications.
[Link] vs Browser JavaScript
Environment:
[Link]: Runs on the server-side, allowing you to build backend services, APIs,
and other server-side applications.
Browser JavaScript: Runs on the client-side, primarily used to create
interactive web pages and handle user interactions.
Global Objects:
[Link]: Has global objects like process, global, and Buffer that are
specific to the server environment.
Browser JavaScript: Has global objects like window, document, and
navigator that are specific to the browser environment.
[Link] vs Browser JavaScript
Modules:
[Link]: Uses the CommonJS module system (require and [Link]) to import
and export modules.
Browser JavaScript: Uses ES6 modules (import and export) for modular code,
though it can also use script tags for loading JavaScript files.
File System Access:
[Link]: Can directly access and manipulate the file system using the
fs module.
Browser JavaScript: Cannot directly access the file system due to
security restrictions.
[Link] vs Browser JavaScript
Networking:
[Link]: Can create TCP/UDP servers, HTTP servers, and other
network-related services.
Browser JavaScript: Limited to making HTTP/HTTPS
requests using XMLHttpRequest or the fetch API.
Advantages of [Link]
High Performance (V8 Engine)
[Link] is built on Google’s V8 JavaScript engine, which compiles JavaScript to machine code.
Cross-Platform Support
[Link] works on Windows, macOS, and Linux.
Can be used to build server-side apps, CLI tools, and even desktop apps ([Link]).
Strong Community & Enterprise Adoption
Large open-source community with constant updates and improvements.
Asynchronous & Non-Blocking I/O
Unlike traditional synchronous models, [Link] is non-blocking, meaning it handles multiple requests
without waiting.
This makes it ideal for I/O-heavy applications (e.g., APIs, real-time apps, and streaming services).
Advantages of [Link]
Single Programming Language (JavaScript)
Since [Link] uses JavaScript, developers can use the same language for both the frontend and backend,
reducing the need to switch contexts and making it easier to share code between the client and server.
Event-Driven Architecture
Uses events and callbacks to handle multiple operations efficiently.
Perfect for real-time applications like chat apps and notifications.
Scalable & Lightweight
Uses a single-threaded event loop, handling thousands of concurrent requests efficiently.
Large Ecosystem (npm)
[Link] has a vast ecosystem of libraries and frameworks available through npm (Node
Package Manager), which makes it easy to add functionality to your applications.
Event Loop
The event loop is the
heart of [Link]. It’s
what allows [Link] to
perform non-blocking
I/O operations despite
being single-threaded.
Here’s how it works:
Event Loop
Single-threaded: [Link] runs on a single thread, meaning it can only
execute one task at a time.
Event-driven: Instead of waiting for tasks (like reading a file or querying
a database) to complete, [Link] offloads these tasks to the system
kernel (which is multi-threaded) and continues executing other code.
Callback Queue: When an asynchronous task (like a file read or network
request) is completed, its callback is placed in the callback queue.
Event Loop: The event loop continuously checks the callback queue and
executes the callbacks one by one when the main thread is free.
Non-blocking I/O
Non-blocking I/O
Blocking I/O:
In traditional server-side languages like PHP or Java, each request
blocks the thread until the I/O operation (e.g., reading a file or
querying a database) is complete. This can lead to performance
bottlenecks when handling many requests.
Non-blocking I/O:
In [Link], I/O operations are asynchronous. Instead of waiting for
the operation to complete, [Link] continues executing other code.
Once the I/O operation is done, a callback is triggered to handle the
result.
[Link] Architecture
V8 Engine
[Link] is built on Chrome’s V8 JavaScript engine, which compiles JavaScript into machine code for
high performance.
V8 is written in C++ and is responsible for executing JavaScript code at lightning speed.
Libuv
Libuv is a C library that provides [Link] with the event loop and asynchronous I/O capabilities.
It handles tasks like file system operations, networking, and threading in the background.
Libuv is what makes [Link] capable of handling thousands of concurrent connections.
Event-driven Architecture
[Link] uses an event-driven architecture, where actions (like incoming HTTP requests) trigger
events.
These events are handled by callback functions, which are executed asynchronously.
Phases of the Event Loop
The Event Loop operates in a
cycle of phases, each
responsible for handling
specific types of tasks.
Here’s a breakdown of the
phases:
Phases of the Event Loop
Phases of the Event Loop
Timers Phase:
Executes callbacks scheduled by setTimeout() and setInterval().
The Event Loop checks if the timer has expired and executes the callback if it
has
Pending Callbacks Phase:
Executes I/O-related callbacks that were deferred from the previous cycle.
For example, if a network request completes, its callback is executed here.
Idle, Prepare Phase:
Internal use only. Used for housekeeping and preparation for the next
phase.
Phases of the Event Loop
Poll Phase:
Waits for I/O events (e.g., file reads, database queries).
If no timers are scheduled, it waits for new I/O events.
If timers are scheduled, it moves to the Timers phase.
Check Phase:
Executes setImmediate() callbacks after the Poll phase.
Close Callbacks Phase:
Handles cleanup tasks like [Link]('close') or file streams closing.
Microtasks vs. Macrotasks
Microtasks:
Higher-priority tasks, such as [Link](). and Promise
callbacks
These are executed immediately after the current phase and
before moving to the next phase.
Macrotasks:
Lower-priority tasks, such as setTimeout(), setImmediate(), and I/O
callbacks.
These are executed in the respective phases of the Event Loop.
Microtasks vs. Macrotasks
Exampl Outp
e ut
[Link]('Start');
setTimeout(() => {
[Link]('Timeout callback’);
}, 0);
[Link]().then(() => {
[Link]('Promise
callback’);
});
[Link]('End');
Modules
[Link] is a self-contained block of code that encapsulates
related functionality. Modules help in:
Code organization: Breaking down large codebases into
smaller, manageable files.
Reusability: Writing code once and reusing it across multiple
parts of an application.
Encapsulation: Keeping variables and functions private unless
explicitly exported.
Types of Modules
Core Modules (Built-in Modules)
Local Modules (Custom Modules)
Third-Party Modules (npm Packages
Core Modules
These are built-in modules
provided by [Link].
Examples: fs, http, path, os,
events, etc.
Core modules do not need to
be installed; they can be
imported directly.
Local Modules
These are user-defined
modules created by
developers.
Local modules are files that
export functionality using
[Link] or exports.
Third-party Modules
These are external modules installed via npm (Node
Package Manager).
Examples: express, lodash, mongoose, etc.
Third-party modules are installed in the node_modules
folder.
Module Loading System in
[Link]
[Link] supports different ways to load modules:
CommonJS (require) - Default in [Link]
ES Modules (import/export) - Used in modern
JavaScript
CommonJS (require) – Default
Used in older versions of [Link].
Loads modules synchronously.
Uses [Link] and require().
Works without additional
configuration.
ES Modules (import/export)
Introduced in ECMAScript 2015
(ES6).
Supports asynchronous loading.
Uses import and export.
Requires [Link] configuration.
REPL
REPL stands for Read-Eval-Print Loop. It is an interactive
programming environment that allows you to execute
JavaScript code in real-time. [Link] comes with a built-in
REPL that you can use to experiment with JavaScript code, test
small snippets, or debug code without needing to create a file.
Read: Reads the input from the user (e.g., JavaScript code).
Eval: Evaluates the input (executes the code).
Print: Prints the result of the evaluation to the console.
Loop: Repeats the process until the user exits the REPL.
OS Module
The os module in [Link]
provides methods to
interact with the operating
system and get system-
related information. It’s a
built-in module, so you
don’t need to install it—
just require it in your
code.
path Module
The path module provides
utilities for working with
file and directory paths in
[Link]. It helps handle
file system paths across
different operating
systems (Windows uses \,
Linux/macOS uses /).