Node Js
Node Js
js
earlier websites were mainly static, and the data displayed by those websites was in HTML form which was
not very interactive. Presently, the websites have become very user-friendly (using javascript) and include
various intensive operations like fetching data from any external API. To handle these types of operations, a
developer needs to know Asynchronous programming in Nodejs. Javascript is a single-threaded,
synchronous programming language which means the execution of statements takes place one step at a time.
However, if we want to fetch data from any API, it can take any amount of undetermined time, which can
depend on Network speed, Server availability, and connection traffic. If API calls were performed in a
synchronous manner, then the browser would not be able to maintain interactive behavior (like taking any
kind of input from the user, like scrolling, mouse click, or button press) until that API request is complete.
This is known as blocking nature. In contrast, asynchronous programming is a technique that ensures non-
blocking code execution.To prevent blocking nature, the browser has numerous Web APIs that JavaScript
can access that are asynchronous in nature. It means the statements can run in parallel with other operations.
The Event Loop in Node.js was designed to aid with the interactions between the main application thread
and asynchronous components
In Node.js, file reading operations are typically performed asynchronously using the fs (file system) module.
Here's an example of an asynchronous file reading program in Node.js:
const fs = require('fs');
if (err) {
return;
});
Import fs Module:
The program starts by importing the fs module, which provides file system-related functionality.
const fs = require('fs');
The variable filePath is set to the path of the file you want to read asynchronously.
The fs.readFile function is used to read the contents of the specified file asynchronously.
// Callback function
});
'utf8': The encoding of the file. In this case, it's set to UTF-8 to read the file as a text file.
The callback function: It is executed once the file reading operation is complete. It takes two parameters:
err: An error object. If an error occurred during the file reading process, this parameter will contain
information about the error.
Callback Function:
Inside the callback function, we check for errors. If there is an error, we log an error message. If there is no
error, we log the content of the file.
if (err) {
return;
Outside the fs.readFile call, we log a message to indicate that the file reading operation is being performed
asynchronously.
What is a Callback?
A callback function is a simple javascript function that is passed as an argument to another function and is
executed when the other function has completed its execution. In layman's terms, a callback is generally
used as a parameter to another function
btn.addEventListener('click', clicked)
})
setTimeout(() => {
const foodDescription = {
order: 3,
meal: 'Burger',
drink: 'Sprite'
callback(foodDescription);
}, 5000)
}
// calling the foodOrder function and passing a callback function as a parameter
console.log(foodDescription)
});
In this above example, we have passed a callback function as the second argument to foodOrder, allowing us
to use it in our asynchronous setTimeout function. This callback is used for logging our foodData in the
console after 5 seconds. What is Callback Hell in NodeJs?
Callback functions are a useful way to confirm the delayed execution of a function until another function
completes its execution and returns with data. However, we may need to nest callbacks inside callbacks, and
this nested nature of callbacks can scale horizontally and become unreadable as well as messy if you have a
lot of consecutive asynchronous requests that rely on each other. This nesting of callbacks is known as node
js callback hell or the Pyramid of Doom.
EVENT LOOP
The earlier websites were mainly static, and the data displayed by those websites was in HTML form which
was not very interactive. Presently, the websites have become very user-friendly (using javascript) and
include various intensive operations like fetching data from any external API. To handle these types of
operations, there is a model called the Asynchronous programming model in Nodejs.
Since javascript is a single-threaded language, it means all the operations are executed by a single thread.
Javascript has a single call stack which also means the execution of statements takes place one step at a time.
In this scenario, if we want to fetch data from any API, it can take any amount of undetermined time, which
can depend on Network speed, Server availability, and connection traffic. Fetching data is a processing-
heavy function; when the fetchAPI() function is added to a call stack, so the js engine would have to wait
for a long amount of time to move to the next statement.
This is known as blocking nature. Most of the browsers do not wait for much longer and will give a pop-up
showing that the Page is Unresponsive, asking if you want to close the web page. While the stack is blocked
by a processing-heavy function, Users will not be able to interact with the application in any form as the
Node.js runtime environment only has a single thread and can only process one statement at a time
There is more to the above scenario; there are many C/ C++ API's asynchronous (I/O) input/output and
interactions with the operating system (OS) that allow the execution of code in a multithreading threading
manner without the shortcomings of the memory. The Event Loop in Node.js was designed to aid with the
interactions between the main application thread and asynchronous components.
Event-Driven Programming
An event loop in Node.js is an event-listener that operates inside the Node.js environment and is always
ready to attend, process, and output an event. Event-driven programming is a programming paradigm in
which the program flow depends on the actions performed by the user. It helps avoid complexity and
collision issues.
Event-driven programming is based on the following concepts :
Event Loop that listens for event triggers and calls the required event handler.
Event Handler is a function that performs some actions for a particular event happening.
Every time you interact with a website through it's interface, like scrolling or clicking a button to open a
new link etc.; an event is happening. These events have an associated callback function with it, and when
triggered, they are executed by the event loop in Node.js.
It allows excellent separation of responsibility without stopping components from working together.
The Event loop is an endless loop that waits for the events and executes them by pushing tasks into the call
stack.
The event loop continuously monitors the call stack, and when the call stack is empty, the event loop pushes
the task from the callback queue to call the stack.
The event loop basically helps us the javascript engine in the execution of the asynchronous callbacks and
promises.
The event loop in node.js gives priority to the microtask queue more than macrotask queue.
Timers
Waiting / Preparation
I/O Polling
setImmediate() callbacks
Close events
Phase 1 : The callbacks of timers in javascript (setInterval, setTimeout) are kept in a heap memory until
they expire. If there are any callbacks associated with any expired timer in the heap memory, the event loop
in Node.js executes them in ascending order of delay time. However, the execution of the callbacks is
controlled by the Poll phase of the event loop.
Phase 2 : In this phase, the event loop in Node.js executes system-related callbacks. Let us say we make a
node server and run it on a port, but that port is used by some other process. Node.js will throw an
error ECONNREFUSED. Some of the systems may want the callback to wait for completion due to some
other tasks that the OS is processing. Thus these callbacks are added to the pending callback queue for
execution.
Phase 3 : During this phase, the event loop does nothing much. The event loop is idle and generally gathers
information and plans what needs to be executed during the next phase. There is no mechanism that could
guarantee code execution during this phase.
Phase 4 : During this phase, the event loop in Node.js watches out for new async I/O callbacks except
the setImmediate, setInterval, setTimeout, and other closing callbacks. The event loop in Node.js does two
things in this phase:
If there are some remaining callbacks in the poll phase queue, it will execute those until the queue is empty.
If there are none, the event loop will stay in the poll phase for some time. This time depends on the
following:
The first case is when there are callbacks in the setImmediate queue, the event loop will not stay for a long
time and will go to the next phase. Again, it will start executing the callbacks until the check phase callback
queue is empty.
The second case is when the event loop gets to know there are some callbacks associated with an expired
timer that are waiting to be executed. The event loop will move to the next phase,
i.e. Check/setImmediate and then to the Closing callbacks phase.
Phase 5 : During the phase, the event loop in Node.js takes the callbacks from the Check phase's queue and
starts executing until the queue is cleared. The event loop in Node.js will come to this phase when there are
no callbacks remaining poll phase.
Phase 6 : During this phase, the event loop in Node.js executes the callbacks associated with the closing
events like process.exit() or socket.on('close', fn).
REPL
Node.js is a server-side Javascript run-time environment that is open source and based on Chrome's
JavaScript Engine (V8). Node.js is based on an event-driven, non-blocking I/O architecture that can be used
for constructing fast and scalable applications.
REPL (READ, EVAL, PRINT, LOOP) is a command-line environment equivalent to Shell in Unix/Linux.
Node comes with the REPL environment when it is installed. The system communicates with the user by
displaying the results of instructions executed by it. It is handy for both the development and debugging
processes. All the parts of REPL have a specific task.
Read: The input provided by the user is read. After necessary parsing, the information is saved in the
memory.
Eval: The data structure with the parsed information is evaluated, and a result is generated.
Print: The result generated after the evaluation is displayed to the user.
Loop: All the above three steps are looped until the user presses ctrl+c twice to get out of the loop.
REPL Environment
The repl.REPLServer class is exported by the node:repl module. When repl.REPLServer instances are
running, they will take individual lines of user input, evaluate them using a user-defined evaluation function,
and print the result. Input and output can come via stdin and stdout, respectively, or from any Node js
stream.
Repl.REPL Server instances include features such as multi-line inputs, automatic input completion, ANSI-
styled output, saving and restoring current REPL session state, error recovery, and customizable evaluation
functions.
If Node.js is installed in your system, then REPL is also present automatically. We use the node command to
launch our Node.js scripts. You can start REPL by typing node on the shell/console
$ node
>
The > symbol indicates that you can insert JavaScript code. Any code entered is instantly evaluated.
>5+6
11
To leave the REPL, type .exit or hit CTRL+D once or press CTRL+C twice. All these will make you exit
the REPL and return to the shell prompt.
The REPL allows you to quickly test and evaluate JavaScript code without the need to save the code in a
file. In the REPL, any kind of javascript or Node.js expression that does not contain any error can be
executed easily.
The Node REPL is intelligent enough to recognize when you haven't finished writing your code and will
switch to a multi-line mode to allow you to enter additional code.
Because the REPL observed an open curly bracket, it makes an assumption that you are writing multi-line of
code, which must be indented. The REPL inserts three dots and a space to the next line to indent the
following code.
There are some shortcuts provided by the REPL to reduce the time required to write commands wherever
possible. The history of all the commands executed in the session is saved by the REPL, and we can go
through them and reuse any command.
Commands Description
up/down keys It is used to see command history and modify previous commands.
ctrl + d It terminates the node repl.
ctrl + c It is used to terminate the current command.
ctrl + c twice It terminates the node repl.
tab keys It specifies the list of the current command.
MODULES
In Node.js, modules are reusable pieces of code that can be encapsulated and organized to perform specific
functionalities. There are different types of modules in Node.js, and they serve various purposes. Here are
the main types:
1. Core Modules:
These are modules that come pre-installed with Node.js, and you can use them without installing any
additional packages. Examples include:
fs (File System): Provides methods for interacting with the file system.
http and https: Used for building HTTP and HTTPS servers and clients.
2. Local Modules:
These are modules created by the developer and used within their own Node.js application. Local modules
are usually organized into separate files to keep the codebase modular and maintainable. They can be loaded
using the require function.
Example:
// myModule.js
module.exports = () => {
// app.js
myModule();
3. Third-Party Modules:
These are modules created by the Node.js community and made available through the npm (Node Package
Manager) registry. Developers can use npm to install third-party modules and include them in their projects.
4. Built-in Modules:
These are modules that are included with Node.js but are not part of the core modules. They still come pre-
installed and do not require additional installation. Examples include:
querystring: Provides methods for parsing and formatting URL query strings.
Introduced in ECMAScript 2015 (ES6), these modules allow developers to use the import and export syntax
for defining and including modules. Node.js has added support for ES6 modules, and they can be used
alongside the traditional CommonJS modules.
Example: // math.js
// app.js
Node.js core modules cover a wide range of functionalities. Here are some of the key ones:
fs (File System): Provides methods for interacting with the file system, including reading and writing files,
creating directories, etc.
http and https: Allow you to create HTTP and HTTPS servers and clients for handling web-related tasks.
path: Assists with file path manipulation, making it easier to work with file and directory paths.
os: Provides operating system-related utility methods, such as retrieving information about the system's
CPUs, memory, and network interfaces.
events: Implements the EventEmitter class, which allows objects to emit and listen for events.
util: Offers utility functions for various purposes, such as formatting and inspecting objects.
These core modules are integral to building a wide range of applications in Node.js, and they provide the
foundation for more specialized functionalities available through local, third-party, and built-in modules.