0% found this document useful (0 votes)
3 views

Theory

The document discusses modules, NPM, NPM init, package managers, NPX, Node.js, key features of Node.js including asynchronous I/O and NPM, why Node.js is single threaded, and scaffolding in Node.js.

Uploaded by

amaldevpanil100
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Theory

The document discusses modules, NPM, NPM init, package managers, NPX, Node.js, key features of Node.js including asynchronous I/O and NPM, why Node.js is single threaded, and scaffolding in Node.js.

Uploaded by

amaldevpanil100
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Modules

● In programming, modules are self-contained units of code that encapsulate related


functionality and can be reused across different parts of a program or shared across
different programs. They help organize code into logical and modular components,
promoting code reusability, maintainability, and separation of concerns..
● Modules define their own scope, and specific functions, variables, or classes can be
exported from a module for use in other modules.
● Modules can be used to encapsulate related code, provide an interface to interact
with the functionality they offer, and prevent naming conflicts between different parts
of a program. They promote code organization, maintainability, and code reuse by
allowing developers to import and use modules where needed, rather than
duplicating code or implementing the same functionality multiple times.
NPM
● NPM (Node Package Manager) is a package manager for JavaScript and the default
package manager for Node.js. It is used to manage and install libraries, frameworks,
and tools that are written in JavaScript and can be used in both server-side (Node.js)
and client-side (browser) applications.
● With NPM, developers can easily install and manage third-party libraries and
modules to incorporate functionality into their projects. NPM provides a command-
line interface (CLI) that allows developers to interact with the package registry, install
packages, update packages, and manage dependencies.
● NPM works by using a file called "package.json" that resides in the root directory of a
project. This file contains metadata about the project, including its dependencies,
scripts, and other configuration details. When you run the command "npm install" in
the project's directory, NPM reads the package.json file, resolves the dependencies
listed within it, and installs the necessary packages into a folder called
"node_modules."
● NPM has a vast and diverse ecosystem of packages, ranging from utility libraries to
full-fledged frameworks. It simplifies the process of sharing and reusing code in the
JavaScript community, allowing developers to focus on building their applications
more efficiently.
NPM init
● The `npm init` command is used to initialize a new Node.js project and create a
`package.json` file.
● The `package.json` file is an important file in a Node.js project. It holds details about
the project dependencies, scripts, project metadata, and other configurations. It is
used by npm to manage and install packages, run scripts, and maintain project
information.
● By running `npm init` and completing the prompts, you can quickly create a
`package.json` file for your Node.js project and start managing your project's
dependencies and scripts using npm.

Package Manager
● A package manager is a software tool that helps developers manage and install
dependencies, libraries, frameworks, and other software packages required for their
projects. It automates the process of downloading, installing, configuring, and
updating packages, making it easier to incorporate external code into a project.
● Package managers streamline the process of managing dependencies, simplify the
installation and update process, and help ensure that projects have the required
dependencies in a consistent and reproducible manner. They play a crucial role in
modern software development by promoting code reuse, improving project
maintainability, and enhancing collaboration within the developer community.
NPX
● NPX is a command-line tool that comes bundled with NPM (Node Package Manager)
starting from version 5.2.0. It stands for "Node Package Executor" and is used to
execute Node.js packages directly without the need to install them globally or locally.
○ A command line tool, also known as a command line utility or command-line
application, is a software program that is designed to be executed and
controlled through a command line interface (CLI). Instead of using a
graphical user interface (GUI), command line tools are operated by typing
commands and arguments directly into a terminal or command prompt.
● When you run a command with NPX, it checks if the package is installed locally or in
the project's dependencies. If it finds the package, it executes the command using
that package. If the package is not found, NPX downloads and installs it temporarily
before executing the command. This ensures that you have the latest version of the
package without explicitly installing it.
● Overall, NPX simplifies the process of executing command-line tools and utilities,
eliminates the need for global installations, and ensures that you have the latest
version of the required packages for your projects.
What is node.js
● Node.js is an open-source, cross-platform JavaScript runtime environment built on
the Chrome V8 JavaScript engine. It allows developers to run JavaScript code
outside of a web browser, on the server-side, enabling the development of scalable
and high-performance network applications.
● Traditionally, JavaScript was primarily used for client-side scripting in web browsers.
However, Node.js extends its usage to server-side development, providing a runtime
environment that allows JavaScript to be executed on servers. This brings the
benefits of JavaScript, such as its event-driven and non-blocking I/O model, to
server-side applications.
Key features of Node.js include:
● Asynchronous and Non-blocking I/O: Node.js uses an event-driven architecture and
a non-blocking I/O model, which allows it to handle concurrent connections
efficiently. This makes it well-suited for building applications that require handling
multiple connections, such as real-time applications, chat servers, or streaming
applications.
● Non-Blocking: Non-Blocking nature of node.js simply means that node.js proceeds
with the execution of the program instead of waiting for long I/O operations or HTTP
requests. i.e the non-JavaScript related code is processed in the background by
different threads or by the browser which gets executed when node.js completes
execution of the main program and when the data required is successfully fetched.
This way, the long time taking operations do not block the execution of the remaining
part of the program. Hence the name Non-Blocking.
● JavaScript Everywhere: Node.js enables developers to use JavaScript for both client-
side and server-side development. This means that developers can use the same
language and code across different layers of an application, improving code reuse
and productivity.
● NPM (Node Package Manager): Node.js comes with NPM, a powerful package
manager that provides access to a vast ecosystem of open-source libraries and
modules. NPM makes it easy to install, manage, and share reusable code, speeding
up development and allowing developers to leverage existing solutions.
● Scalability: Node.js is known for its ability to handle a large number of concurrent
connections with low resource consumption. Its lightweight and event-driven nature
make it a good choice for building highly scalable applications.
● Server-side Web Development: Node.js has gained popularity in web development,
providing frameworks such as Express.js, Nest.js, and Koa.js that simplify the
creation of web servers and APIs. It allows developers to build fast, efficient, and
real-time web applications.
● Node.js is used by many large companies and organizations to build a wide range of
applications, including web servers, microservices, real-time applications, APIs,
command-line tools, and more. It has a vibrant and active community that continues
to contribute to its growth and development.
WHY is node.js single threaded
● The use of a single thread in Node.js is a deliberate design choice that aims to
provide certain advantages and optimize the execution of JavaScript code in specific
scenarios. Here are some reasons behind the single-threaded nature of Node.js:
○ Asynchronous and Non-Blocking I/O
○ Scalability and Performance
○ Event Loop Efficiency
● While the single-threaded nature of Node.js provides benefits in certain use cases,
it's important to note that it may not be suitable for all types of applications. CPU-
bound tasks or computationally intensive operations can potentially block the event
loop and impact the responsiveness of the application. To address this, Node.js
allows for offloading such tasks to worker threads or external processes while
keeping the main event loop free for handling I/O operations.
● Overall, the single-threaded model in Node.js is a trade-off that prioritizes scalability,
performance, and simplified programming models for I/O-intensive applications and
real-time, event-driven scenarios.
Scaffolding in node.js
● In Node.js, scaffolding refers to the process of generating the basic structure, files,
and code for a Node.js project or application. It sets up the initial directory structure,
configures essential files, and creates boilerplate code to help developers get started
quickly. Scaffolding in Node.js is typically done using scaffolding tools or generators
that automate the process like
○ Express Generator
○ Nest CLI
○ Yeoman
○ Koa Generator
● By using a scaffolding tool, developers can save time by avoiding manual setup
tasks, such as creating directories, configuring project files, and writing initial
boilerplate code. They can focus on building the application's core functionality rather
than dealing with repetitive setup tasks.
● It's worth noting that while scaffolding tools provide a starting point, developers can
customize and extend the generated code and structure according to their specific
requirements.
Types of stream
● In Node.js, streams are a core concept that provide a way to handle continuous data
flows, whether it's reading from or writing to a source. Streams allow for efficient
handling of large amounts of data by processing it in small chunks, rather than
loading the entire data set into memory at once. There are several types of streams
in Node.js:
○ Readable Streams: Readable streams are used for reading data from a
source. They emit 'data' events when new data is available and 'end' event
when all data has been read. Readable streams can be consumed in various
ways, such as reading data synchronously or asynchronously, or by piping
them to writable streams.
■ Piping is a powerful concept in Node.js streams that allows you to
connect the output of one stream to the input of another stream,
creating a data flow pipeline. It simplifies the process of reading data
from a source and writing it to a destination by handling the data
transfer automatically.
○ Writable Streams: Writable streams are used for writing data to a destination.
They provide a way to write data in chunks and handle it as it becomes
available. Writable streams have methods to write data, handle drain events
for flow control, and emit 'finish' event when all data has been written.
○ Duplex Streams: Duplex streams are both readable and writable. They can be
used for bidirectional data flow, where data can be both written to and read
from the stream. Duplex streams implement both the Readable and Writable
interfaces.
○ Transform Streams: Transform streams are a special type of duplex stream
that allows for data modification while it is being read or written. They take
input data, perform some processing or transformation on it, and then output
the modified data. Transform streams are commonly used for tasks like
compression, encryption, data parsing, or serialization.
○ Object Mode Streams: In addition to the aforementioned stream types,
Node.js streams can also operate in object mode. Object mode streams allow
reading and writing JavaScript objects rather than just binary or string data.
This mode can be useful when working with structured data or when passing
objects between streams.
● Node.js provides a rich set of built-in modules for working with streams, including the
'stream' module, 'fs' module for file system streams, and 'http' module for network
streams. These stream types and modules offer flexibility and efficiency when
dealing with data of various sizes and formats in Node.js applications.
Stream vs buffer
● In summary, buffers are used for working with fixed-size blocks of data in memory,
while streams are used for handling continuous data flow and processing data in
smaller chunks. Buffers are suitable for working with finite amounts of data, while
streams are more efficient for processing large or ongoing data streams.
Core Modules
● Node.js provides a set of core modules that are available out-of-the-box without the
need for any external dependencies. These core modules offer various functionalities
to facilitate different aspects of development. Here are some of the core modules in
Node.js:
○ fs: The fs module provides file system-related operations such as reading,
writing, and manipulating files and directories.
○ http: The http module enables the creation of HTTP servers and clients,
allowing you to handle HTTP requests, build web servers, and make HTTP
requests to other servers.
○ https: The https module is similar to the http module but provides HTTPS
(HTTP Secure) functionality for secure communication over SSL/TLS.
○ path: The path module offers utilities for working with file paths. It helps in
resolving, joining, normalizing, and manipulating file and directory paths
across different operating systems.
○ events: The events module provides an event-driven architecture and allows
you to create and handle custom events.
○ util: The util module offers various utility functions that are helpful for
debugging, formatting, and working with objects, including inheritance and
type checking.
○ querystring: The querystring module provides utilities for parsing and
formatting URL query strings.
○ crypto: The crypto module provides cryptographic functionality, including
encryption, decryption, hashing, and generating secure random numbers.
○ stream: The stream module allows for streaming data, providing the
foundation for reading from or writing to data sources in chunks rather than
loading everything into memory at once.
○ os: The os module provides operating system-related information and utilities,
such as retrieving system information, interacting with the file system, and
working with network interfaces.
○ process: The process module provides information and control over the
current Node.js process, including accessing command-line arguments,
environment variables, and process-related events.
● These are just a few examples of the core modules available in Node.js. Each
module offers its own set of functionalities to assist in different areas of application
development. These core modules, along with the vast ecosystem of third-party
modules available through NPM (Node Package Manager), make Node.js a powerful
platform for building a wide range of applications.
DNS module
● The DNS (Domain Name System) module in Node.js provides functionality for
working with DNS-related operations. It allows you to perform DNS lookups, resolve
domain names, query DNS servers, and perform reverse DNS lookups. The DNS
module is built-in in Node.js, so no external installation is required.
Types of middleware
● In software development, middleware refers to software components or modules that
sit between different layers or components of an application. Middleware acts as a
bridge, facilitating communication, data processing, and functionality between various
parts of an application. In the context of web development, middleware is often used
in frameworks and server-side technologies to handle request/response processing.
Here are some common types of middleware:
○ 1. HTTP Middleware: HTTP middleware is used in web development
frameworks to intercept and process HTTP requests and responses. It sits
between the web server and the application, allowing developers to add
custom functionality, perform authentication, handle routing, apply security
measures, and modify request/response objects.
○ 2. Logging Middleware: Logging middleware captures and logs information
about requests and responses flowing through an application. It helps in
debugging, monitoring, and analyzing application behavior, performance, and
errors.
○ 3. Error Handling Middleware: Error handling middleware is responsible for
catching and processing errors that occur during the execution of an
application. It can handle and format errors, log them, and send appropriate
error responses to clients.
○ 4. Authentication Middleware: Authentication middleware is used to
authenticate and authorize users accessing an application. It verifies user
credentials, manages sessions, and enforces access controls based on
authentication status and user roles.
○ 5. Caching Middleware: Caching middleware stores the response of a request
and serves it directly from the cache for subsequent identical requests,
reducing the need to reprocess the same data or execute the same logic
repeatedly.
● Depending on the application's requirements, developers can leverage existing
middleware or create custom middleware to add specific functionality and behaviour
to their applications.
Body-parser
● body-parser is a Node.js middleware used to parse the body of incoming HTTP
requests. It extracts data from the request body and makes it available in a more
accessible format for further processing.
More concepts in Node and Express
● Here are a few additional concepts related to Node.js and the Express framework
that you might find useful:
○ Event-driven architecture: Node.js follows an event-driven, non-blocking I/O
model. This means that it uses event loops to handle multiple concurrent
operations efficiently. Instead of waiting for each operation to complete before
moving to the next one, Node.js initiates operations and continues executing
other tasks. When an operation completes, a corresponding event is
triggered, and the application can respond accordingly.
○ Package management with NPM: Node.js comes with NPM (Node Package
Manager), which is a powerful package manager. NPM allows you to install,
manage, and share reusable code packages/modules, including frameworks,
libraries, and tools. It simplifies dependency management and makes it easy
to integrate third-party code into your applications.
○ Express.js: Express is a popular, minimalist web application framework for
Node.js. It provides a robust set of features and utilities for building web
applications and APIs. Express simplifies routing, middleware handling, and
request/response handling, allowing you to create server-side applications
quickly and efficiently.
○ Routing: In Express, routing refers to defining how the application responds to
different HTTP requests. With Express's routing capabilities, you can define
routes for various URLs and HTTP methods (e.g., GET, POST, PUT,
DELETE). Each route can be associated with a specific callback function that
handles the request and generates a response.
○ Middleware: Express middleware functions are functions that have access to
the request and response objects and the next middleware function in the
application's request-response cycle. Middleware functions can perform
actions such as modifying the request/response objects, adding custom
functionality, handling authentication, error handling, logging, and more.
Middleware functions can be applied globally or to specific routes.
○ Template engines: Express supports various template engines such as EJS,
Pug (formerly Jade), Handlebars, and more. Template engines enable you to
generate dynamic HTML by embedding variables and logic within the
template files. Express seamlessly integrates with these template engines,
allowing you to render dynamic views for your web application.
○ Error handling: In Express, error handling is typically done through
middleware functions. You can define custom error handling middleware that
catches and processes errors occurring during request processing. This
middleware can handle errors, log them, and send appropriate error
responses to clients.
○ RESTful APIs: Express is often used for building RESTful APIs. REST
(Representational State Transfer) is an architectural style that uses HTTP
methods and URLs to represent resources and perform operations on them.
Express provides a clean and structured way to define routes and handle
different HTTP methods for building RESTful APIs.
○ WebSocket support: While Express is primarily designed for HTTP
request/response handling, you can use additional libraries such as Socket.IO
to enable WebSocket communication in your Express application. WebSocket
allows for real-time, bidirectional communication between the client and
server, making it suitable for applications like chat systems, real-time
notifications, and collaborative platforms.
● These concepts should give you a good foundation for working with Node.js and
Express. Remember to refer to the official documentation and explore additional
resources to delve deeper into these concepts and further enhance your skills with
these technologies.
Libuv
● Libuv is a multi-platform library that provides the core asynchronous I/O
(Input/Output) operations for Node.js. It is responsible for abstracting the underlying
operating system's I/O capabilities and providing a consistent API for handling I/O
operations in an event-driven, non-blocking manner.
● Overall, Libuv plays a critical role in the core functionality of Node.js, enabling it to
handle asynchronous I/O operations efficiently, provide an event-driven architecture,
and support cross-platform development. It abstracts low-level I/O details, allowing
developers to focus on writing asynchronous JavaScript code without having to worry
about the specific platform intricacies.
● Here are some key features and components of Libuv:
○ Event loop
● The event loop is a crucial component of asynchronous programming in
JavaScript and is at the heart of how Node.js operates. It is responsible for
managing the execution of code and handling I/O operations efficiently.
● In Node.js, the event loop enables non-blocking I/O operations, allowing the
application to handle multiple concurrent operations without getting blocked or
slowing down. It follows an event-driven architecture, where code execution is
driven by events and callbacks rather than a traditional sequential flow.
● Here's a simplified overview of how the event loop works:
○ 1. Event Queue: The event loop starts by processing any pending
events in the event queue. Events can include user actions (e.g.,
clicking a button), timer events, I/O events (e.g., reading from a file),
or network events (e.g., receiving an HTTP response).
○ 2. Event Handlers: When an event is encountered, the associated
event handler or callback function is executed. The event handlers
typically perform some asynchronous operation, such as reading from
a file or making a network request.
○ 3. Non-Blocking I/O: While the event handler is performing an
asynchronous operation, it registers a callback function to be executed
when the operation is complete. The event loop moves on to the next
event in the queue, ensuring that other operations can be processed
concurrently.
○ 4. Event Completion: Once an asynchronous operation (e.g., file read
or network request) completes, the corresponding callback function is
placed in the event queue to be executed by the event loop.
○ 5. Callback Execution: The event loop continues to process events
from the queue, executing the callback functions associated with
completed operations. This allows the application to respond to events
as they occur.
● Event-Driven Architecture: is a software design pattern where the flow of
the program is determined by events that occur asynchronously. Instead of
following a sequential execution model, the architecture revolves around
events and event handlers. Events can be triggered by various sources such
as user interactions, timers, network requests, or system notifications. When
an event occurs, the associated event handler or callback function is
executed to respond to the event.

● By utilizing the event loop, Node.js can handle a large number of concurrent
operations efficiently without blocking the execution of other code. This event-
driven approach is well-suited for handling I/O-intensive tasks and building
scalable, high-performance applications.
● It's important to note that while the event loop enables non-blocking I/O, long-
running or CPU-intensive operations can still block the event loop and affect
the responsiveness of the application. To handle such scenarios, Node.js
provides mechanisms such as worker threads and the child process module
to offload CPU-bound tasks to separate threads or processes.
● Understanding the event loop is crucial for writing efficient and responsive
Node.js applications. It allows developers to leverage asynchronous
programming patterns and take full advantage of Node.js's non-blocking I/O
capabilities.
● Thread Pool:
● Libuv includes a thread pool that can be utilized for performing
computationally intensive or blocking operations in separate threads.
● By offloading such operations to the thread pool, Node.js can keep the event
loop free and responsive to other asynchronous I/O tasks.
● Asynchronous I/O
● Cross-Platform Support
● Timers and Event Handling
Synchronous and asynchronous
● Synchronous and asynchronous are two different execution models that describe
how tasks or operations are carried out in a system, typically in the context of
programming or computing.
● Synchronous Execution:
○ In synchronous execution, tasks are performed one after the other in a
sequential manner. Each task must complete before the next one can begin.
When a task is initiated, the program waits until it finishes executing before
moving on to the next task. Synchronous operations are blocking, meaning
they can halt the execution of the program until they are completed. This can
cause delays and inefficiencies, especially if a task takes a long time to
complete.
● Asynchronous Execution:
○ In asynchronous execution, tasks can start, run, and complete independently
of one another. When an asynchronous task is initiated, the program does not
wait for it to finish before moving on to the next task. Instead, it continues
executing the remaining tasks or operations. Asynchronous operations are
non-blocking, allowing the program to perform other tasks while waiting for a
particular operation to complete. Once an asynchronous task finishes, a
callback function or other mechanism is typically used to handle the result or
notify the program.
○ Asynchronous execution is particularly useful in scenarios where tasks may
take a significant amount of time to complete, such as network requests, file
I/O, or database queries. By allowing the program to continue execution while
waiting for these tasks to finish, asynchronous operations can improve the
overall responsiveness and efficiency of an application. They enable
concurrent execution and can prevent blocking situations that could cause the
program to become unresponsive.
● In summary, synchronous execution follows a sequential and blocking approach,
where each task must complete before the next one starts. Asynchronous execution
allows tasks to run independently and concurrently, enabling the program to continue
execution while waiting for certain operations to complete.
Callback
● A callback, in the context of programming, refers to a function that is passed as an
argument to another function. The purpose of a callback function is to be invoked or
called by the receiving function at a specific point in its execution or in response to a
certain event.
● Callbacks are commonly used in asynchronous programming or event-driven
architectures, where tasks or operations may take time to complete, and the program
needs to continue executing without waiting for the task to finish. Instead of blocking
the execution, the program can provide a callback function to be called when the task
is complete or when a certain event occurs.
● Callbacks allow for dynamic and flexible control flow, enabling code to be executed in
response to specific events or conditions. They are often used in scenarios such as
handling the results of asynchronous operations, handling user interactions, event
handling in graphical user interfaces, and more.
● It's worth noting that callbacks can also be implemented as anonymous functions
directly passed as arguments to the receiving function, without explicitly defining a
separate named function.
set timeout
● The term "set timeout" refers to a function or method available in many programming
languages and environments that allows you to delay the execution of a specified
block of code or a function call after a certain amount of time has passed. It is
commonly used to introduce a delay or schedule the execution of code in the future.
● The purpose of using setTimeout can vary depending on the use case. It can be
used for various purposes, such as introducing a delay before performing a certain
action, scheduling the execution of code at a specific time in the future, or
implementing animations and timed events in web applications.
● It's important to note that setTimeout is a non-blocking function, meaning that after
setting the timeout, the program continues executing the remaining code without
waiting for the timeout to complete.
REPL
● REPL stands for "Read-Eval-Print Loop." It is an interactive programming
environment commonly used in interpreted languages like Python, JavaScript, and
Ruby. The REPL provides a way to execute code snippets or expressions and
immediately see the results.
● In a REPL, the user inputs a command or code snippet, which is then evaluated,
executed, and the result is displayed. The cycle repeats, allowing the user to
experiment, test code, and get immediate feedback.
● The three components of a REPL are:
○ Read: The user inputs a line or block of code to be executed.
○ Eval: The inputted code is evaluated, meaning it is parsed and processed by
the interpreter or compiler.
○ Print: The result of the evaluated code is displayed or printed to the user.
● After printing the result, the REPL goes back to the read step, waiting for the next
input.
● REPLs are commonly used for various purposes, including:
○ Quick code prototyping: Developers can quickly test and experiment with
code snippets without the need for a full-fledged application or script.
○ Debugging: REPLs allow developers to interactively test and debug their
code, inspecting variables and expressions on the fly.
○ Learning and education: REPLs provide an interactive learning environment
where beginners can experiment with code and immediately see the results.
● For JavaScript, the Node.js platform provides a REPL environment called the Node.js
REPL. The Node.js REPL allows you to interactively run JavaScript code,
experiment, and get immediate feedback. To access the Node.js REPL, you need to
have Node.js installed on your computer.
Event driven programming
● Event-driven programming in JavaScript is a paradigm where the flow of the program
is determined by events and the associated event handlers. Instead of following a
sequential execution path, the program waits for specific events to occur and then
reacts to those events by invoking the corresponding event handlers.
● JavaScript provides a robust event-driven model, particularly in the browser
environment, where numerous events can occur, such as user interactions (e.g.,
mouse clicks, keyboard input), network activity (e.g., data received from a server), or
timer events
● Event-driven programming is especially prevalent in JavaScript frameworks like
React.js, Angular, and Node.js. These frameworks provide more advanced event
handling capabilities and abstractions, allowing developers to build complex and
interactive applications.
● By leveraging event-driven programming, JavaScript applications can respond to
user interactions, handle data asynchronously, and create dynamic and interactive
user experiences.
HTTTP METHODS- GET, PUT, POST, DELETE, PATCH
● The terms you mentioned refer to different HTTP methods used in web development
to perform various operations on resources. Here's a brief explanation of each
method:
○ 1. GET: The GET method is used to retrieve data from a server. It requests a
representation of the specified resource and does not modify any data on the
server.
○ 2. POST: The POST method is used to send data to the server to create a
new resource. It submits data to be processed by the server and can result in
the creation of a new resource or the modification of existing resources.
○ 3. PUT: The PUT method is used to update or replace an existing resource
with new data. It sends the entire representation of the resource to be
updated to the server.
○ 4. DELETE: The DELETE method is used to remove a specified resource
from the server. It instructs the server to delete the specified resource.
○ 5. PATCH: The PATCH method is used to partially update an existing
resource. Unlike the PUT method that requires sending the entire updated
representation, PATCH sends only the changes or differences to be applied
to the resource.
● These HTTP methods are commonly used in combination with RESTful APIs
(Representational State Transfer) to interact with server resources over the web.
Each method serves a specific purpose in performing different operations on the
resources.
HOSTING
● Hosting refers to the process of storing and making a website, application, or other
digital content accessible and available to users over the internet. It involves
providing server resources and infrastructure to store the files and data associated
with the website or application and making them accessible to visitors or users.
● When you host a website or application, you essentially rent server space or use a
server infrastructure provided by a hosting service provider. This server infrastructure
is typically maintained in data centers with high-speed internet connections and other
necessary resources to ensure the website or application can be accessed reliably.
● Hosting can be classified into various types, including:
○ Shared Hosting: In shared hosting, multiple websites are hosted on a single
server, with resources shared among them. It is a cost-effective option but
may have limitations on performance and scalability.
○ VPS (Virtual Private Server) Hosting: VPS hosting involves dividing a physical
server into multiple virtual servers, providing more control, privacy, and
dedicated resources compared to shared hosting.
○ Dedicated Hosting: With dedicated hosting, you have an entire physical
server dedicated to your website or application. It offers the highest level of
control, performance, and flexibility but comes at a higher cost.
○ Cloud Hosting: Cloud hosting utilizes a network of interconnected servers to
provide scalability, flexibility, and reliability. It allows for easy scaling of
resources based on demand.
● Hosting providers typically offer additional services such as server management,
security, backups, and technical support to ensure the smooth operation of hosted
websites or applications.
● Overall, hosting enables individuals and businesses to make their websites or
applications available to users worldwide by storing and serving the necessary files
and data from servers connected to the internet.
Timing features
● setTimeout(), setImmediate(), and setInterval() methods.
● eg:callback: This parameter holds the function that to be called when the timer
elapse.
● delay: This parameter holds the number of milliseconds to wait before calling the
vallback function.
● args: This parameter holds the optional arguments for the function.
view engine
● A view engine is a component or module in a web application framework that allows
developers to generate dynamic HTML pages by combining data with pre-defined
templates. It provides a structured way to render and display data to the user,
typically in response to a client request.
● View engines separate the presentation layer (HTML) from the logic and data
manipulation code of the application. They provide a template language or syntax
that allows developers to define the structure of the HTML page and embed
placeholders or tags that will be dynamically populated with data.
● When a client request is received, the server-side code retrieves the necessary data
and passes it to the view engine. The view engine then renders the data into the
appropriate places within the template, generating a complete HTML page. The
resulting HTML is then sent as a response to the client, which can be displayed in the
browser.
● View engines often provide additional features such as layout support, partial views,
conditional rendering, iteration over data collections, and more. These features help
in creating reusable and modular views, improving code organization and
maintainability.
● Some popular view engines in web development include:
○ EJS (Embedded JavaScript): EJS allows embedding JavaScript code within
HTML templates, making it easy to generate dynamic content.
○ Handlebars: Handlebars provides a syntax for defining templates with
placeholders and supports logic constructs like conditionals and loops.
○ Pug (formerly Jade): Pug uses indentation-based syntax and provides a
concise and expressive way to define templates.
○ Twig: Twig is a flexible and secure template engine commonly used with the
Symfony framework.
● The choice of a view engine depends on the specific framework or technology being
used in web development. View engines help developers separate concerns and
achieve a clean separation of presentation and application logic, making it easier to
build and maintain dynamic web applications.
Namespace js
● In JavaScript, namespaces are a way to organize code and prevent naming conflicts
by creating a container for variables, functions, and objects. They provide a level of
encapsulation and help maintain a modular and organized codebase.
Runtime environment
● A runtime environment, also known as an execution environment, is a software
framework or platform that provides the necessary infrastructure and services for
executing and running computer programs. It consists of various components,
libraries, and tools that enable the execution of code written in a particular
programming language.
Npm vs npx
● In summary, npm is primarily used for managing dependencies and packages for
your JavaScript projects, while npx is used for executing command-line tools and
executables from npm packages without the need for global installations. They are
both valuable tools in the JavaScript ecosystem and are often used together to
manage dependencies and run command-line tools efficiently.
event-driven program vs event-driven architecture
● In summary, an event-driven program is one that responds to events during runtime,
where the flow of execution is driven by events. On the other hand, event-driven
architecture is an architectural style that structures a system around events,
promoting loose coupling and enabling communication between components through
events. While event-driven programming focuses on the implementation of individual
programs, event-driven architecture encompasses the design and structure of entire
systems.
Morgan
● Morgan is a popular logging middleware for Node.js web applications. It provides
HTTP request logging capabilities, allowing developers to track and monitor incoming
requests to their application.
● Morgan offers various logging formats that developers can choose from, including
predefined formats such as "combined", "common", "dev", and "short". These formats
determine the structure and level of detail in the logged messages.
● When the dev logging format is used, morgan will log concise output to the console,
which is helpful during development and debugging. The logged information typically
includes the request method, URL, response status code, response time, and the
size of the response body.
CORS and same origin policy
● The Same Origin Policy is a default security measure in browsers that restricts cross-
origin requests, while CORS is a mechanism that relaxes the Same Origin Policy and
enables controlled access to resources from different origins by specifying CORS
headers in server responses. CORS provides a way to configure cross-origin access
permissions for specific resources, domains, methods, headers, and credentials.
Event emitter
● In JavaScript, an Event Emitter is a design pattern or a mechanism that allows
objects to emit and listen for custom events. It enables communication and
coordination between different parts of a program by providing a way to send and
receive notifications about specific events or state changes.
other nodejs frameworks
● Express.js
● Koa.js
● Nest.js
● Hapi.js
generator function
● A generator function is a special type of function in JavaScript that can be paused
and resumed during its execution. It allows you to define an iterative algorithm by
writing code that can yield multiple values over time, rather than executing all the
code at once and returning a single value.
process.nextTick
● process.nextTick() is a method provided by the Node.js runtime that allows you to
schedule a function to be executed on the next iteration of the event loop. It provides
a way to defer the execution of a function until the current operation completes and
the event loop becomes idle.
● Environment variables are commonly used to store sensitive information like API
keys, database credentials, or configuration settings that may vary across different
deployment environments (e.g., development, staging, production). They allow
applications to be configured without hardcoding values, making them more flexible
and secure.
● Note that changes to environment variables generally require restarting the Node.js
process to take effect. Additionally, environment variables are typically set outside of
the Node.js application code and can be managed by deployment tools, configuration
files, or container orchestration systems.
Process.env
● process.env is an object in Node.js that provides access to the environment variables
of the current process. Environment variables are key-value pairs that are part of the
operating system's environment in which the Node.js process is running. They are
used to configure and customize the behavior of applications based on the specific
environment in which they are deployed.
"Error first callback"
● is a convention used in Node.js for handling asynchronous operations that involve
callbacks. It is a pattern where the first parameter of a callback function is reserved
for an error object, allowing for consistent error handling
● In the error first callback pattern, when an asynchronous operation completes, it
invokes the callback with two parameters: the first parameter is an error object (if an
error occurred), and the second parameter (or subsequent parameters) contain the
result or data of the operation. The consumer of the callback can then check the error
parameter to determine if an error occurred and handle it accordingly.
console. error vs console.warning
● In summary, console.error() is used to log critical error messages, while
console.warning() or console.warn() is used to log warning messages. They serve
different purposes and are often used to convey the severity or importance of the
logged messages.
Query and route parameters
● Query Parameters:
○ Query parameters are a way to pass data to the server as part of the URL.
They are typically used for filtering, sorting, or specifying additional
information for a resource.
○ Query parameters are appended to the URL after a question mark (?) and are
in the form of key-value pairs, separated by ampersands (&).
○ In Node.js, query parameters can be accessed from the req.query object
when handling HTTP requests. The req.query object is populated with the
parsed query parameters.
● Route Parameters:
○ Route parameters are placeholders in the URL path that capture dynamic
values. They are used to define variable parts of a URL.
○ Route parameters are defined in the route path by prefixing a colon (:)
followed by the parameter name.
○ In Node.js, route parameters can be accessed from the req.params object
when handling HTTP requests. The req.params object contains the values of
the route parameters.
● Query parameters and route parameters serve different purposes. Query parameters
are used for providing additional information in the URL, while route parameters
capture dynamic values from the URL path. They are both useful for extracting data
from the request URL and using it in your server-side logic.
cookies and sessions
● In summary, cookies are client-side storage mechanisms that store small amounts of
data on the user's browser, while sessions are server-side mechanisms that store
user-specific data and maintain state between requests. Cookies are often used to
identify and personalize user experiences, while sessions are used for more sensitive
and application-specific purposes.
● Cookies:
○ Cookies are small pieces of data stored on the client-side (in the user's
browser) as key-value pairs.
○ They are primarily used to store user-specific information or session data that
needs to persist across multiple requests.
○ Cookies are set by the server and sent along with each subsequent request
from the client to the server.
○ The server can read and write cookies using the HTTP headers Set-Cookie
and Cookie.
○ Cookies can have an expiration time, after which they are automatically
deleted by the client's browser, or they can be session cookies that are
deleted when the browser is closed.
○ Cookies are often used for tasks like maintaining user authentication,
remembering user preferences, tracking user behavior, and implementing
features like shopping carts.
○ However, it's important to note that cookies are stored on the client-side and
can be accessed or modified by the client, so sensitive information should not
be stored directly in cookies.
● Sessions:
○ Sessions are server-side mechanisms used to store user-specific data and
maintain state between multiple requests.
○ A session is created on the server when a user visits a website and is
identified by a unique session identifier (usually stored in a cookie).
○ The session identifier is sent to the client as a cookie, allowing the server to
associate subsequent requests from the same client with the corresponding
session data.
○ Session data is stored on the server and can contain any type of information
relevant to the user session.
○ Sessions are typically used to store sensitive information related to
authentication, such as user IDs, access tokens, or user-specific data that
should not be exposed to the client.
○ Session data is often stored in server memory or in a database, depending on
the implementation and the specific requirements of the application.
○ Sessions provide a way to maintain user context and perform user-specific
operations without relying solely on cookies.

Server communication
● Server communication refers to the process of exchanging data or information
between a client (such as a web browser or a mobile app) and a server. It involves
making requests from the client to the server and receiving responses in return.
● The choice of the communication method depends on the specific requirements of
the application, including factors such as real-time updates, data size, scalability, and
the desired level of interactivity between the client and server.
HTTP vs HTTPS
● HTTPS provides a secure and encrypted connection between clients and servers,
protecting sensitive data from eavesdropping and unauthorised access. It is essential
for websites that handle sensitive information and is increasingly becoming the
preferred protocol for secure web communication.
request and response header
● Request and response headers are part of the HTTP (Hypertext Transfer Protocol)
protocol used for communication between clients (such as web browsers) and
servers. Headers contain additional information about the request or response,
providing context and instructions for handling the data being exchanged.
● Headers play a crucial role in the communication process, allowing clients and
servers to exchange information and instruct each other on how to handle the
request or response. They enable customization, control, and coordination between
the different components involved in the HTTP communication.
node blocking vs asynchronous
● In Node.js, the terms "blocking" and "asynchronous" refer to different approaches for
handling I/O (Input/Output) operations, such as reading from or writing to files,
making network requests, or accessing databases.
● Node.js is designed to leverage asynchronous I/O and provides an event-driven
architecture that allows developers to write highly scalable and performant
applications. By using non-blocking I/O operations and callbacks or promises,
Node.js can handle high concurrency and efficiently handle multiple I/O tasks without
getting blocked by slow operations.
● It's important to note that while Node.js encourages asynchronous programming
URL Encoder:
● URL Encoder is a mechanism used to convert special characters and non-ASCII
characters in a URL into a format that can be safely transmitted over the internet.
MVC:
● MVC (Model-View-Controller) is a software architectural pattern used to structure
applications. It separates the application into three components: the model (data and
business logic), the view (user interface), and the controller (handles user
interactions and updates the model and view).
Prototype Inheritance:
● Prototype Inheritance is a mechanism in JavaScript that allows objects to inherit
properties and methods from a prototype object. Objects can have a prototype object
from which they inherit properties and behavior.
Prototype Chaining:
● Prototype Chaining is the process of traversing the prototype chain to access
properties and methods of an object's prototype and its parent prototypes.
Scope Temporal Dead Zone:
● The Temporal Dead Zone refers to the period in JavaScript between the creation of a
variable using let or const and its declaration, where accessing the variable results in
a ReferenceError.
Shallow Cloning and Deep Cloning:
● Shallow cloning creates a new object with the same properties as the original object,
but the properties that are objects are still references to the original object. Deep
cloning creates a new object with entirely new copies of all nested objects and
properties.
Structured Cloning:
● Structured Cloning is a mechanism in JavaScript that allows objects to be serialized
and transferred between different execution contexts, such as web workers or cross-
origin frames.
Scope Chaining (let vs var):
● With let, variables are block-scoped, meaning they are only accessible within the
block they are declared in. With var, variables are function-scoped, meaning they are
accessible within the entire function they are declared in.
indexOf:
● The indexOf method is used to find the index of a specified value within a string or
array. It returns the index of the first occurrence of the value, or -1 if the value is not
found.
Substring:
● Substring is a method used to extract a portion of a string based on its index
positions. It takes a start index and an optional end index and returns the extracted
substring.
Interpreter and Compiler:
● An interpreter translates and executes code line by line, while a compiler translates
the entire code into machine-readable instructions before execution.
Call, Bind, Apply:
● Call: The call() method is used to invoke a function with a specified this value and
arguments provided individually. It takes the function's this context as its first
argument, followed by any additional arguments for the function. The call() method
allows you to borrow a method from one object and invoke it on anot
● Bind: The bind() method creates a new function that, when called, has its this
keyword set to a specified value. It allows you to permanently bind a function to a
specific context. The bind() method returns a new function with the bound context
and any provided arguments.
● Apply: The apply() method is similar to call(), but it takes an array-like object as its
second argument that represents the arguments to be passed to the function. This is
useful when you have an array of values that you want to pass as individual
arguments to a function.
● In summary, call() and apply() allow you to invoke a function with a specific context
and individual or array-like arguments, respectively. On the other hand, bind()
creates a new function with a permanently bound context, which can be called later
with its own arguments.
Prototype vs Proto:
● Prototype refers to the property of a constructor function that is used as a blueprint
for creating objects. Proto is the property of an object that references its prototype.
Object Constructors:
● Object Constructors are functions used to create objects with predefined properties
and methods. They serve as blueprints for creating multiple instances of similar
objects.
ES6 vs ES7:
● ES6 (ECMAScript 2015) and ES7 (ECMAScript 2016) are versions of the
ECMAScript standard that introduced new features to the JavaScript language. ES6
brought significant enhancements, while ES7 introduced smaller additions to the
language.
Pass by Reference & Pass by Value:
● Pass by Reference means that when passing an object as a parameter to a function,
the reference to the object is passed. Changes made to the object inside the function
will affect the original object. Pass by Value means that when passing a primitive
data type as a parameter to a function, a copy of the value is passed. Changes made
to the value inside the function do not affect the original value.
Redirect Issue - Using DOM:
● Redirect issue refers to problems encountered when attempting to redirect a user to
a different page in a web application. Using DOM (Document Object Model)
manipulation, such as setting the window.location property, can be a common
approach to perform a redirect.
Promise.all:
● Promise.all is a method in JavaScript that takes an array of promises and returns a
single promise that is fulfilled when all the promises in the array are resolved. It
allows you to handle multiple asynchronous operations simultaneously.
Error-First Callback:
● Error-First Callback is a common convention in Node.js for handling asynchronous
operations. It involves passing a callback function as the last argument to an
asynchronous function, where the first parameter of the callback is reserved for an
error object (if any), and subsequent parameters hold the result or data.
Query Selector & Query Selector All:
● Query Selector is a method in JavaScript that allows you to select and retrieve the
first matching element in the DOM based on a CSS selector. Query Selector All
returns a NodeList containing all elements that match the provided selector.
Append:
● Append is a method in JavaScript that allows you to add an element or a string of
HTML as a child of another element. It adds the specified content to the end of the
target element.
Create Element:
● Create Element is a method in JavaScript used to dynamically create a new HTML
element. It creates an element node with the specified tag name.
Add Event:
● Add Event is a method in JavaScript used to attach an event listener to an element. It
allows you to specify a function that will be executed when the specified event occurs
on the element.
Blocking Code:
● Blocking code refers to code that causes the program execution to pause until a
particular operation completes. In Node.js, blocking code can negatively impact
performance because it prevents the event loop from processing other events or
requests until the blocking operation finishes.
JSON Parse:
● JSON Parse is a method in JavaScript used to parse a JSON string and convert it
into a JavaScript object. It takes a valid JSON string as input and returns the
corresponding JavaScript object.
JSON Stringify:
● JSON Stringify is a method in JavaScript used to convert a JavaScript object into a
JSON string. It serializes the object, including its properties and values, into a JSON-
formatted string.
Conditional Operator vs Optional Operator:
● The conditional operator (ternary operator) in JavaScript is a concise way to write
conditional expressions. It evaluates a condition and returns one value if the
condition is true and another value if it's false. The optional chaining operator (?.) is
used to access properties or call functions on an object that may be null or
undefined, preventing errors by gracefully handling missing values.
Fork Function:
● Fork function is a concept in programming where a new child process is created from
an existing parent process. The child process runs independently but shares some
resources with the parent process, such as code and memory.
Router.all:
● Router.all is a method in web application frameworks, such as Express.js, used to
define a route handler that handles all HTTP methods (GET, POST, PUT, DELETE,
etc.) for a specific route.
Push to array vs Add to Set:
● Push is a method used to add an element to the end of an array. Add to Set is a
method used to add an element to a Set data structure. The difference is that push
adds the element to an array, allowing duplicates, while add to set adds the element
to a Set, ensuring uniqueness.
Syntax Parsing:
● Syntax Parsing is the process of analyzing the structure and grammar of a
programming language to determine its meaning and validity. It involves breaking
down the code into tokens and applying language rules to understand the code's
structure and identify any syntax errors.

You might also like