0% found this document useful (0 votes)
18 views31 pages

NodeJS Notes

Node.js is an open-source JavaScript runtime built on Chrome's V8 engine, enabling server-side application development with a non-blocking, event-driven architecture. It supports REST APIs, real-time applications, and microservices, and utilizes npm for module management. The V8 engine plays a crucial role in executing JavaScript efficiently, providing performance benefits through Just-In-Time compilation and garbage collection.

Uploaded by

Richa Bandal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views31 pages

NodeJS Notes

Node.js is an open-source JavaScript runtime built on Chrome's V8 engine, enabling server-side application development with a non-blocking, event-driven architecture. It supports REST APIs, real-time applications, and microservices, and utilizes npm for module management. The V8 engine plays a crucial role in executing JavaScript efficiently, providing performance benefits through Just-In-Time compilation and garbage collection.

Uploaded by

Richa Bandal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

NodeJS Notes

[Link] is a powerful, open-source, and cross-platform JavaScript runtime


environment built on Chrome's V8 engine. It allows you to run JavaScript
code outside the browser, making it ideal for building scalable server-side
and networking applications.

 JavaScript was mainly used for frontend development earlier. With


[Link] (introduced in 2009), JavaScript became a backend language
as well.

 Non-blocking, event-driven architecture for high performance.

 Supports the creation of REST APIs, real-time applications,


and microservices.

 Comes with a rich library of modules through npm (Node Package


Manager).

[Link] is a free, open source tool that lets you run JavaScript outside the
web browser.

With [Link], you can build fast and scalable applications like web servers,
APIs, tools, and more.

[Link] uses an event-driven, non-blocking model.

It can handle many connections at once without waiting for one to finish
before starting another.

This makes it great for real-time apps and high-traffic websites.

Here are some examples of what you can build with [Link]:

 Web servers and websites


 REST APIs

 Real-time apps (like chat)

 Command-line tools

 Working with files and databases

 IoT and hardware control

The V8 engine is one of the core components of [Link], and understanding


its role and how it works can significantly improve your understanding of how
[Link] executes JavaScript code. In this article, we will discuss the V8
engine’s importance and its working in the context of [Link].

What is a V8 Engine?
The V8 engine is an open-source JavaScript engine developed by Google. It is
written in C++ and is primarily designed to execute JavaScript code. V8 is
used in multiple applications, especially in Google Chrome, but later utilized
to create [Link] for server-side coding.

V8 compiles JavaScript directly to machine code rather than using an


interpreter. This compilation process allows for the efficient execution of
JavaScript, which is key to the performance benefits in both web browsers
(like Chrome) and [Link] applications.

Role of the V8 Engine in [Link]

[Link] is a JavaScript runtime built on Chrome's V8 engine, which means


that the engine itself is responsible for executing JavaScript code in a [Link]
application. While [Link] provides the environment and APIs for running
JavaScript server-side, the actual execution of the code is handled by the V8
engine.

When you write a [Link] application, the code you write is ultimately
executed by the V8 engine. It converts JavaScript code into machine code
that the system's processor can execute. This helps in fast performance for
server-side applications, making [Link] a popular choice for building
scalable network applications.

How V8 Engine Works?

The V8 engine works by following these basic steps


Step 1. Parsing

 The JavaScript code is initially read by the V8 engine.

 It undergoes parsing, where the code is broken down into smaller units
(tokens) such as keywords, variables, and operators.

Step 2. Ignition Interpreter

 After parsing, the engine uses the Ignition Interpreter to convert the
tokens into ByteCode.

 ByteCode is an intermediate, low-level representation of the code. This


allows for quick execution without waiting for full compilation.

Step 3: Optimization

 While the code is being executed by the Ignition interpreter, V8 uses


the Turbofan Compiler to look for parts of the code that are executed
frequently (like loops or functions).

 These frequently executed parts are optimized into machine code,


which is faster to execute.

Step 4: Turbofan Compiler

The Turbofan Compiler compiles frequently used code into Optimized


Machine Code. This machine code is specific to the underlying hardware and
is much faster than ByteCode.

Step 5: Execution
The machine code generated by the Turbofan compiler is now executed. This
results in the JavaScript program running and producing the desired output.

Step 6: Deoptimization

 If there are changes (such as variable types changing unexpectedly),


the machine code may no longer be applicable. In this case, V8 will
deoptimize that part of the code and send it back to the Ignition
interpreter for recompilation.

 Deoptimization ensures that the generated machine code remains


correct and efficient as the code evolves at runtime.

This cycle continues, with V8 optimizing, executing, and occasionally


deoptimizing the code to ensure high performance during runtime.

Key Features of the V8 Engine

The V8 engine comes with several important features that contribute to the
performance and efficiency of [Link] applications:

 Just-In-Time (JIT) Compilation: It compiles JavaScript code into


machine code at runtime, making the code execution process much
faster. This is one of the main reasons why V8 is considered so fast and
efficient.

 Garbage Collection: V8 includes an advanced garbage collector that


automatically manages memory. It identifies and removes unused
objects, preventing memory leaks and ensuring that your [Link]
applications don’t consume unnecessary memory over time.

 Optimization: It is designed to optimize code execution as it runs. It


monitors the execution of functions and optimizes those that are
frequently called, improving performance.

 Supports ES6+ Features: It supports all the features introduced in


ES6, ES7, and subsequent versions of JavaScript like classes, template
literals, promises, and async functions.

Why is V8 Important for [Link]?

The V8 engine is a core part of [Link]. Here’s why it’s so important

 Performance and Speed: V8’s JIT compilation and optimization


techniques allow [Link] to handle large volumes of I/O-bound tasks
and requests efficiently. This makes [Link] suitable for building high-
performance applications such as real-time chat apps, streaming
services, and APIs.

 Asynchronous Nature of [Link]: V8 complements the


asynchronous, non-blocking nature of [Link]. Since V8 compiles code
efficiently and runs it fast, it enables [Link] to handle many I/O
operations concurrently without getting bogged down.

 Memory Management: V8’s garbage collection ensures that [Link]


applications can run smoothly over time by freeing up memory that's
no longer needed. This is crucial for long-running server-side
applications that need to manage memory effectively.

 Cross-Platform Compatibility: Since the V8 engine is used in both


Google Chrome and [Link], it ensures that developers can use the
same codebase across both client-side (browser) and server-side
([Link]) environments. This creates a consistent development
experience.

 Real-Time Applications: The performance optimizations provided by


V8 make it an excellent choice for building real-time applications, such
as chat applications, live updates, and online gaming, where speed and
low latency are critical.

V8 Optimization Techniques

V8 uses a variety of optimization techniques to improve the performance of


JavaScript execution in [Link]:

 JIT Compilation: V8’s Just-In-Time (JIT) compilation helps to speed up


the execution of JavaScript code. By compiling JavaScript into machine
code during runtime, V8 ensures that frequently executed code paths
are executed much faster.

 In-place Updates: V8 performs in-place updates on memory objects,


reducing the need for memory allocation and deallocation. This makes
it faster and reduces the overhead of memory management.

 Inline Caching: V8 uses inline caching to optimize property lookups,


reducing the need to repeatedly search for the same properties in
objects. This improves performance, especially in dynamic code
scenarios.

Performance Benefits of V8 in [Link]


The performance of [Link] is largely driven by the efficiency of the V8
engine. Here’s how V8 contributes to the performance of [Link]
applications:

 Fast Code Execution: V8’s JIT compilation ensure that [Link]


applications run at high speed. Since V8 compiles JavaScript to
machine code, it eliminates the need for interpretation, making code
execution faster.

 Efficient Memory Management: V8’s garbage collector prevents


memory leaks and ensures that unused memory is freed up. This is
crucial for long-running applications, especially in server-side
environments like [Link].

 Non-blocking, Asynchronous Nature: V8’s efficient execution and


[Link]’s non-blocking architecture enable handling multiple tasks
simultaneously without blocking the event loop. This makes [Link]
ideal for I/O-intensive applications, such as real-time chat apps and
APIs.

 Cross-Platform Compatibility: V8 allows [Link] to be used across


various platforms, such as Windows, Linux, and macOS, ensuring that
developers can use the same codebase for both server-side and client-
side development.

Can [Link] work without V8?

 No, [Link] cannot work without V8.

 V8 is an essential part of [Link] as it is the JavaScript engine that


executes the JavaScript code.

 [Link] is built on top of the V8 engine, using it to run JavaScript


outside the browser. V8 compiles and executes the code, making
[Link] capable of running server-side JavaScript.

 In simpler terms, V8 handles the core task of converting JavaScript into


machine code that can be executed by the computer, which is why it is
crucial for [Link]'s functioning.

 Without V8 or a similar JavaScript engine, [Link] would not be able to


process or run JavaScript code.

REST API
REST API stands for Representational State Transfer API. It is a type of API
(Application Programming Interface) that allows communication between
different systems over the internet. REST APIs work by sending requests and
receiving responses, typically in JSON format, between the client and server

 A request is sent from the client to the server via a web URL, using one
of the HTTP methods.

 he server then responds with the requested resource, which could be


HTML, XML, Image, or JSON, with JSON being the most commonly used
format for modern web services.

 These methods map to CRUD operations (Create, Read, Update,


Delete) for managing resources on the web.

Note => REST is an architectural design style for APIs, while HTTP is the
communication protocol used for data transfer over the web. REST APIs use
HTTP methods to interact with resources, but they are not the same thing.
REST defines how the APIs should behave, while HTTP defines the rules for
communication over the web. They commonly work together, but they serve
different purposes.

Common HTTP Methods Used in REST API

In HTTP, there are five methods that are commonly used in a REST-based
Architecture, i.e., POST, GET, PUT, PATCH, and DELETE. These correspond to
create, read, update, and delete (or CRUD) operations, respectively. There
are other methods that are less frequently used, like OPTIONS and HEAD.

1. GET Method

The HTTP GET method is used to read (or retrieve) a representation of a


resource. In the safe path, GET returns a representation in XML or JSON and
an HTTP response code of 200 (OK). In an error case, it most often returns a
404 (NOT FOUND) or 400 (BAD REQUEST).

GET /users/123

This request fetches data for the user with ID 123.

2. POST Method

The POST method is commonly used to create new resources. It is often used
to create subordinate resources related to a parent resource. Upon
successful creation, the server returns HTTP status 201 (Created) along with
a Location header pointing to the newly created resource.

POST /users
{
"name": "Anjali",
"email": "gfg@[Link]"
}

This request creates a new user with the given data.

NOTE: POST is neither safe nor idempotent.

3. PUT Method

PUT is an HTTP method used to update or create a resource on the server.


When using PUT, the entire resource is sent in the request body, and it
replaces the current resource at the specified URL. If the resource doesn’t
exist, it can create a new one.

PUT /users/123
{
"name": "Anjali",
"email": "gfg@[Link]"
}

This request updates the user with ID 123 or creates a new user if one
doesn't exist.

4. PATCH Method

PATCH is an HTTP method used to partially update a resource on the server.


Unlike PUT, PATCH only requires the fields that need to be updated to be sent
in the request body. It modifies specific parts of the resource rather than
replacing the entire resource.
PATCH /users/123
{
"email": "[Link]@[Link]"
}

This request updates only the email of the user with ID 123, leaving the rest
of the user data unchanged.

Differences Between PUT & PATCH

Both PATCH and PUT are used to update resources on the server, but they
differ in how they handle the update process:

PUT PATCH

Replaces the entire resource Updates only specified fields

Must send full data Only sends changes

Idempotent Not always idempotent

Example: Updating a Example: Changing just a


user’s entire profile user’s email

5. DELETE Method

It is used to delete a resource identified by a URI. On successful deletion,


return HTTP status 200 (OK) along with a response body.

DELETE /users/123

This request deletes the user with ID 123.

Idempotence: An idempotent HTTP method is a HTTP method that can be


called many times without different outcomes. It would not matter if the
method is called only once, or ten times over. The result should be the same.
Again, this only applies to the result, not the resource itself.

Building a Simple REST API using [Link] and Express

Now let's create a REST AP and perform the various HTTP operations.
Step 1: Create the folder

Create the NodeJs project by using the following command:

mkdir node-app
cd node-app

Step 2: Install the [Link]

npm init -y

Step 3: Install Express

To begin building a REST API in [Link], you need to install Express. Run the
following command in your terminal:

npm install express

Step 4: Create the Server

Here’s a basic example of creating a REST API in [Link] using Express

// Import the Express module

const express = require('express');

const app = express();

const port = 3000;

[Link]([Link]());

// Define a route for GET requests

[Link]('/users', (req, res) => {

[Link]({ message: 'Returning list of users' });

});

// Define a route for POST requests

[Link]('/users', (req, res) => {

const newUser = [Link];


[Link]({ message: 'User created', user: newUser });

});

// Define a route for PUT requests

[Link]('/users/:id', (req, res) => {

const userId = [Link];

const updatedUser = [Link];

[Link]({ message: `User with ID ${userId} updated`, updatedUser });

});

// Define a route for DELETE requests

[Link]('/users/:id', (req, res) => {

const userId = [Link];

[Link]({ message: `User with ID ${userId} deleted` });

});

// Start the server

[Link](port, () => {

[Link](`Server is running on [Link]

});

Output: To test the API, open [Link] in Postman or another


API testing tool.

In this example

 GET /users: This route fetches the list of users (or mock data in this
case).

 POST /users: This route accepts JSON data from the client to create a
new user.
 PUT /users/:id: This route updates the information of a user based on
the user ID provided in the URL.

 DELETE /users/:id: This route deletes a user with the specified ID.

Features of REST APIs

 Stateless: Each request from a client to a server must contain all the
information the server needs to fulfill the request. No session state is
stored on the server.

 Client-Server Architecture: RESTful APIs are based on a client-


server model, where the client and server operate independently,
allowing scalability.

 Cacheable: Responses from the server can be explicitly marked as


cacheable or non-cacheable to improve performance.

 Uniform Interface: REST APIs follow a set of conventions and


constraints, such as consistent URL paths, standardized HTTP methods,
and status codes, to ensure smooth communication.

 Layered System: REST APIs can be deployed on multiple layers,


which helps with scalability and security.

Real world Example of Rest APIs :

REST APIs are widely used across various industries to simplify


communication between systems. Some common applications include:

 Social Media: Integrating third-party platforms like Facebook, Twitter,


and Instagram for features like login, sharing, and posting.

 E-Commerce: Managing products, processing payments, handling


orders, and customer management.

 Geolocation Services: GPS tracking, real-time location updates, and


location-based services like finding nearby places.

 Weather Forecasting: Fetching weather data from external sources


to provide real-time weather updates and forecasts.

Microservices
Microservices are an architectural approach to developing software
applications as a collection of small, independent services that communicate
with each other over a network.

 Instead of building a monolithic application where all the functionality


is tightly integrated into a single codebase, microservices break down
the application into smaller, loosely coupled services.

 Can be written in a variety of programming languages, and


frameworks, and each service acts as a mini-application on its own.

 A small, loosely coupled service that is designed to perform a specific


business function and each microservice can be developed, deployed,
and scaled independently.

How do Microservices work?

 Each microservice handles a particular business feature, like user


authentication or product management, allowing for specialized
development.

 Services interact via APIs, facilitating standardized information


exchange and integration.

 Different technologies can be used for each service, enabling teams to


select the best tools for their needs.

 Microservices can be updated independently, reducing risks during


changes and enhancing system resilience.

Main components of Microservices Architecture

Main components of microservices architecture include:


 Microservices: Small, loosely coupled services that handle specific
business functions, each focusing on a distinct capability.

 API Gateway: Acts as a central entry point for external clients also
they manage requests, authentication and route the requests to the
appropriate microservice.

 Service Registry and Discovery: Keeps track of the locations and


addresses of all microservices, enabling them to locate and
communicate with each other dynamically.

 Load Balancer: Distributes incoming traffic across multiple service


instances and prevent any of the microservice from being
overwhelmed.

 Containerization: Docker encapsulate microservices and their


dependencies and orchestration tools like Kubernetes manage their
deployment and scaling.

 Event Bus/Message Broker: Facilitates communication between


microservices, allowing pub/sub asynchronous interaction of events
between components/microservices.

 Database per Microservice: Each microservice usually has its own


database, promoting data autonomy and allowing for independent
management and scaling.

 Caching: Cache stores frequently accessed data close to the


microservice which improved performance by reducing the repetitive
queries.

 Fault Tolerance and Resilience Components: Components like


circuit breakers and retry mechanisms ensure that the system can
handle failures gracefully, maintaining overall functionality.

Design Patterns for Microservices Architecture

Below are the main design pattern of microservices:

1. API Gateway Pattern

API Gateway pattern simplifies the client’s experience by hiding the


complexities of multiple services behind one interface. It can also handle
tasks like authentication, logging, and rate limiting, making it a crucial part
of microservices architecture.
2. Service Registry Pattern

Service Registery pattern is like a phone book for microservices. It maintains


a list of all active services and their locations (network addresses). When a
service starts, it registers itself with the registry.

Other services can then look up the registry to find and communicate with it.
This dynamic discovery enables flexibility and helps services interact without
hardcoding their locations.

3. Circuit Breaker Pattern

In circuit breaker pattern If a service fails repeatedly, the circuit breaker trips,
preventing further requests to that service. After a timeout period, it allows
limited requests to test if the service is back online. This reduces the load on
failing services and enhances system resilience.

4. Saga Pattern

Saga pattern is useful for managing complex business processes that span
multiple services. Instead of treating the process as a single transaction, the
saga breaks it down into smaller steps, each handled by different services.

If one step fails, compensating actions are taken to reverse the previous
steps. This way, you maintain data consistency across the system, even in
the face of failures.

5. Event Sourcing Pattern

In Event Sourcing Pattern, Each event describes a change that occurred,


allowing services to reconstruct the current state by replaying the event
history. This provides a clear audit trail and simplifies data recovery in case
of errors.

6. Strangler Pattern

Strangler pattern allows for a gradual transition from a monolithic application


to microservices. New features are developed as microservices while the old
system remains in use.

Over time, as more functionality is moved to microservices, the old system is


gradually "strangled" until it can be fully retired. This approach minimizes
risk and allows for a smoother migration.

7. Bulkhead Pattern
Similar to compartments in a ship, the bulkhead pattern isolates different
services to prevent failures from affecting the entire system.

If one service encounters an issue, it won’t compromise others. By creating


boundaries, this pattern enhances the resilience of the system, ensuring that
a failure in one area doesn’t lead to a total system breakdown.

8. API Composition Pattern

When you need to gather data from multiple microservices, the API
composition pattern helps you do so efficiently.

A separate service (the composition service) collects responses from various


services and combines them into a single response for the client. This
reduces the need for clients to make multiple requests and simplifies their
interaction with the system.

9. CQRS Design Pattern

CQRS Design Pattern divides the way data is handled into two parts:
commands and queries. Commands are used to change data, like creating or
updating records, while queries are used just to fetch data. This separation
allows you to tailor each part for its specific purpose.

Real-World Example of Microservices

Let's understand the Miscroservices using the real-world example of Amazon


E-Commerce Application:

Amazon’s online store runs on many small, specialized microservices, each


handling a specific task. Working together, they create a smooth shopping
experience.

Below are the microservices involved in Amazon E-commerce Application:


 User Service: Handles user accounts and preferences, making sure
each person has a personalized experience.

 Search Service: Helps users find products quickly by organizing and


indexing product information.

 Catalog Service: Manages the product listings, ensuring all details


are accurate and easy to access.

 Cart Service: Lets users add, remove, or change items in their


shopping cart before checking out.

 Wishlist Service: Allows users to save items for later, helping them
keep track of products they want.

 Order Taking Service: Processes customer orders, checking


availability and validating details.

 Order Processing Service: Oversees the entire fulfillment process,


working with inventory and shipping to get orders delivered.

 Payment Service: Manages secure transactions and keeps track of


payment details.

 Logistics Service: Coordinates everything related to delivery,


including shipping costs and tracking.

 Warehouse Service: Keeps an eye on inventory levels and helps with


restocking when needed.

 Notification Service: Sends updates to users about their orders and


any special offers.

 Recommendation Service: Suggests products to users based on


their browsing and purchase history

How to migrate from Monolithic to Microservices Architecture?

Below are the main the key steps to migrate from a monolithic to
microservices architecture:
Step 1: Begin by evaluating your current monolithic application. Identify
its components and determine which parts can be shifted to microservices.

 Step 2: Break down the monolith into specific business functions. Each
microservice should represent a distinct capability that aligns with your
business needs.

 Step 3: Implement the Strangler Pattern to gradually replace parts of


the monolithic application with microservices. This method allows for a
smooth migration without a complete transition at once.

 Step 4: Establish clear APIs and contracts for your microservices. This
ensures they can communicate effectively and interact seamlessly.

 Step 5: Create Continuous Integration and Continuous Deployment


(CI/CD) pipelines. This automates testing and deployment, enabling
faster and more reliable releases.

 Step 6: Introduce mechanisms for service discovery so that


microservices can dynamically locate and communicate with each
other, enhancing flexibility.

 Step 7: Set up centralized logging and monitoring tools. This provides


insights into the performance of your microservices, helping to identify
and resolve issues quickly.

 Step 8: Ensure consistent management of cross-cutting concerns,


such as security and authentication, across all microservices to
maintain system integrity.

 Step 9: Take an iterative approach to your microservices architecture.


Continuously refine and expand your services based on feedback and
changing requirements
Applications of Microservices

 E-commerce platforms: Separate services for inventory, payments,


orders, and user management.

 Banking & FinTech: Independent services for accounts, transactions,


fraud detection, and customer support.

 Streaming services (e.g. Netflix, Spotify): Services for user


profiles, recommendations, content delivery, and billing.

 Travel & Booking systems: Services for flights, hotels, payments,


and notifications.

 Healthcare systems: Patient records, appointment scheduling,


billing, and reporting as separate services.

 Social media platforms: Microservices for feed, chat, notifications,


and user profiles.

Benefits and Challenges of using Microservices Architecture

Benefits of Using Microservices Architecture

 Teams can work on different microservices simultaneously.

 Issues in one service do not impact others, enhancing reliability.

 Each service can be scaled based on its specific needs.

 The system can quickly adapt to changing workloads.

 Teams can choose the best tech stack for each microservice.

 Small, cross-functional teams work independently.

Challenges of using Microservices Architecture

 Managing service communication, network latency, and data


consistency can be difficult.

 Decomposing an app into microservices adds complexity in


development, testing and deployment.

 Network communication can lead to higher latency and complicates


error handling.

 Maintaining consistent data across services is challenging, and


distributed transactions can be complex.
Microservices vs. Monolithic Architecture

Below is a tabular comparison between microservices and monolithic


architecture across various aspects:

Microservices Monolithic
Aspect Architecture Architecture

Decomposed into
Single, tightly
small, independent
integrated codebase.
Architecture Style services.

Small, cross-functional
Larger, centralized
Development Team teams for each
development team.
Structure microservice.

Scaling involves
Independent scaling of
replicating the entire
individual services.
Scalability application.

Independent Whole application is


deployment of deployed as a single
Deployment services. unit.

Efficient use of
Resources allocated
resources as services
based on the overall
can scale
application's needs.
Resource Utilization independently.

Faster development Slower development


and deployment and deployment due to
Development Speed cycles. the entire codebase.

Flexibility Easier to adopt new Limited flexibility due


Microservices Monolithic
Aspect Architecture Architecture

technologies for to a common


specific services. technology stack.

Easier maintenance of Maintenance can be


smaller, focused complex for a large,
Maintenance codebases. monolithic codebase

NodeJS NPM

NPM (Node Package Manager) is a package manager for NodeJS modules. It


helps developers manage project dependencies, scripts, and third-party
libraries. By installing NodeJS on your system, NPM is automatically installed
and ready to use.

 It is mainly used to manage packages or modules—these are pre-built


pieces of code that extend the functionality of your NodeJS application.

 The NPM registry hosts millions of free packages that you can
download and use in your project.

 NPM is installed automatically when you install NodeJS, so you don’t


need to set it up manually.

Package in [Link]

A package in NodeJS is a reusable module of code that adds functionality to


your application. It can be anything from a small utility function to a full-
featured library.

 Packages can be installed from the NPM registry.

 They are stored in the node_modules folder in your project.

 You can easily install, update, or remove packages with NPM


commands.

How to Use NPM with NodeJS?

To start using NPM in your project, follow these simple steps


Step 1: Install NodeJS and NPM

First, you need to install NodeJS. NPM is bundled with the NodeJS installation.

Note: You can follow our article to Install the Node and NPM- How to install
Node on your system

Step 2: Verify the Installation

After installation, verify NodeJS and NPM are installed by running the
following commands in your terminal:

node -v

npm -v

These commands will show the installed versions of NodeJS and NPM.

NodeJS NPM Version

Step 3: Initialize a New NodeJS Project

In the terminal, navigate to your project directory and run:

npm init -y

This will create a [Link] file, which stores metadata about your
project, including dependencies and scripts.

Step 4: Install Packages with NPM

To install a package, use the following command

npm install <package-name>

For example, to install the [Link] framework

npm install express

This will add express to the node_modules folder and automatically update
the [Link] file with the installed package information.

Step 5: Install Packages Globally


To install packages that you want to use across multiple projects, use the -g
flag:

npm install -g <package-name>

Step 6: Run Scripts

You can also define custom scripts in the [Link] file under the "scripts"
section. For example:

"scripts": {

"start": "node [Link]"

Then, run the script with

npm start

Using NPM Package in the project

Create a file named [Link] in the project directory to use the package

//[Link]

const express = require('express');//import the required package

const app = express();

[Link]('/', (req, res) => {

[Link]('Hello, World!');

});

[Link](3000, () => {

[Link]('Server running at [Link]

});
 express() creates an instance of the Express app.

 [Link]() defines a route handler for HTTP GET requests to the root (/)
URL.

 [Link]() sends the response “Hello, World!” to the client.

 [Link](3000) starts the server on port 3000, and [Link]()


outputs the server URL.

Now run the application with

node [Link]

Visit [Link] in your browser, and you should see the


message: Hello, World!

Managing Project Dependencies

1. Installing All Dependencies

In a NodeJS project, dependencies are stored in a [Link] file. To install


all dependencies listed in the file, run:

npm install

This will download all required packages and place them in the
node_modules folder.

2. Installing a Specific Package

To install a specific package, use:

npm install <package-name>

You can also install a package as a development dependency using:

npm install <package-name> --save-dev

Development dependencies are packages needed only during development,


such as testing libraries.

To install a package and simultaneously save it in [Link] file (in case


using NodeJS), add --save flag. The --save flag is default in npm install
command so it is equal to npm install package_name command.

Example:

npm install express --save


Usage of Flags:

 --save: flag one can control where the packages are to be installed.

 --save-prod : Using this packages will appear in Dependencies which


is also by default.

 --save-dev : Using this packages will get appear in devDependencies


and will only be used in the development mode.

Note: If there is a [Link] file with all the packages mentioned as


dependencies already, just type npm install in terminal

3. Updating Packages

You can easily update packages in your project using the following command

npm update

This will update all packages to their latest compatible versions based on the
version constraints in the [Link] file.

To update a specific package, run

npm update <package-name>

4. Uninstalling Packages

To uninstall packages using npm, follow the below syntax:

npm uninstall <package-name>

For uninstall Global Packages

npm uninstall package_name -g

Popular NPM Packages for NodeJS

NPM has a massive library of packages. Here are a few popular packages
that can enhance your NodeJS applications

Package
s Description

A fast, minimal web framework for building APIs and web


Express
applications.
Package
s Description

Mongoo
A MongoDB object modeling tool for NodeJS.
se

A utility library delivering consistency, customization, and


Lodash
performance.

Axios A promise-based HTTP client for making HTTP requests.

React A popular front-end library used to build user interfaces.

Dotenv Loads environment variables from a .env file into [Link].

Nodemo Automatically restarts the server during development when file


n changes are detected.

A JavaScript testing framework designed to ensure correctness


Jest
of any NodeJS code.

Socket.i Enables real-time, bidirectional communication between web


o clients and servers.

Versioning in NPM

NPM allows you to manage package versions. This is important when you
want to ensure that a specific version of a library is used across all
environments.

Install a Specific Version

To install a specific version of a package, use:

npm install <package-name>@<version>


For example:

npm install express@4.17.1

This will install version 4.17.1 of Express, regardless of the latest version.

Using Semantic Versioning to manage packages

 To install a package of a specific version, mention the full and exact


version in the [Link] file.

 To install the latest version of the package, mention "*" in front of the
dependency or "latest". This will find the latest stable version of the
module and install it.

 To install any version (stable one) above a given version, mention it like
in the example below: "express":"^4.1.1". in [Link] file. The
caret symbol (^) is used to tell the npm to find a version greater than
4.1.1 and install it.

Dependencies vs DevDependencies

Aspects Dependencies DevDependencies

Required for running the Required only during


application in the development(not in
Purpose production. production).

Examples express, mongoose, nodemon, eslint, jest, moch,


Aspects Dependencies DevDependencies

lodesh, react, axios webpack, babel

Installed using:

npm install <package


Installed using:
name>
npm install <package> --
or
save-dev (or- D)
npm install <package> --
Installation save

Location in
Listed under listed under
[Link]
"dependencies" key "devDependencies" key
n

Yes, included when you run No, ignored when you run
Availability npm install --production. npm install --production.

Directly required for the used for development


app to function(e.g - web tools,testing, linting,
Impact on frameworks, database bundling, but not for running
App drivers etc) the app live.

Command npm install nodemon --save-


npm install express
on Example dev

NPM Audits and Security

NPM provides a built-in audit feature to help developers identify and fix
security vulnerablities in project dependencies. By running npm audit , you
can generate a detailed reports of known issues, their severity levels and
recommended fixes. Using npm audit fix, developers can automatically apply
safe [Link] audits allow applications to remain secure by reducing
risks from vulnerable third party modules.
Let us now take a look at our first code example.

// Import the http module

const http = require("http");

// Create a server

const server = [Link]((req, res) => {

[Link] = 200;

[Link]("Content-Type", "text/plain");

[Link]("Welcome to the [Link] Tutorial");

});

// Listen on port 3000

[Link](3000, () => {

[Link](

"Server is running on [Link]

});

It will start a server, and when you visit [Link] it will display

Welcome to the [Link] Tutorial

 The http module is imported to create a basic HTTP server.

 The createServer() method is used to handle incoming requests and


send responses.

 The server listens on port 3000, and a message is displayed in the


browser when accessed.
NodeJS is a runtime environment for executing JavaScript outside
the browser, built on the V8 JavaScript engine. It enables server-side
development, supports asynchronous, event-driven programming, and
efficiently handles scalable network applications.

You might also like