0% found this document useful (0 votes)
1 views61 pages

Unit-I

Uploaded by

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

Unit-I

Uploaded by

akshitapinjere
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Unit-I

Introduction to Full Stack Development


Framework
• A framework is a platform for developing applications, providing a foundation for building
software applications.
• Framework is a platform for developing applications which provides a foundation on which
software applications can be built. The front-end frameworks are the software packages
that provide -
• The reusable code modules,
• Standardized front end technologies and
• Ready made interface blocks for making the front-end development faster and simple.

Basic concept: A web development framework is a collection of tools, libraries and


technologies that are used to create web applications and websites. It provides a basic
structure and set of conventions for developers to build web applications quickly and
efficiently.
Following are some important reason which indicate why do we use web frameworks –

1. Saves time: The most striking feature of web framework is that it saves time and energy
in developing any app because the developer doesn't need to worry about session
handling, error handling and authentication logic. These functions are taken care of by
web frameworks.

2. Well organized app: The web framework itself takes care of managing directories and files.
This makes the complete application well organized.

3. Flexibility and customizable: Add-ons, themes, plugins, widgets enable rapid


customization on the web application. This brings out a lot of flexibility in code development.

4. Code reusability: Framework also promotes the reuse of code.

5. Security: Framework makes developers sure that the application uses good security
measurements because the framework itself takes care of it.
Web Development Framework
A web development framework is a set of tools and resources that help developers build
and manage websites, web applications, and web services.
Frameworks can help with tasks like:
Database interaction
URL routing
User authentication
Security
Push notifications
Code reusability
Generating HTML from templates
Formatting data as JSON or XML
There are two types of web frameworks:
Client-side framework: Works in the front end and manages the user interface
Server-side framework: Works in the background and ensures the website functions
smoothly
Web Development Framework
A web development framework is a collection of tools, libraries, and technologies used to
create web applications. It simplifies and standardizes the development process.

Components of Web Development Framework


- User
- Browser
- Webserver
- Backend Services
Components of Web Development Framework
Basic diagram of the components of a basic website/web application
User
- Definition: The user interacts with the web application using an interface provided via the
browser.
- The user role in a web framework is to sit on the visual output and interaction input of
- webpages. That is, users view the results of the web framework processing and then
provide
- interactions using mouse clicks, keyboard input, and swipes and taps.
Role:
- Sends requests for services or information.
- Provides inputs to be processed by the web system.
The Browser
The browser plays three roles in the web framework:
■ Provide communication to and from the webserver
■ Interpret the data from the server and render it into the view that the user actually sees
■ Handle user interaction through the keyboard, mouse, touchscreen, or other input device
and take the appropriate action

Browser-to-Webserver Communication
Browser-to-webserver communication consists of a series of requests, using the HTTP and
HTTPS protocols.
Hypertext Transfer Protocol (HTTP) is used to define communication between the browser
and the webserver.
HTTP defines what types of requests can be made as well as the format of those requests
and the HTTP response.
HTTPS adds an additional security layer, SSL/TLS, to ensure secure connections by
requiring the webserver to provide a certificate to the browser.
The user can then determine whether to accept the certificate before allowing the
connection.

There are three main types of requests that a browser will make to a webserver:
■ GET: The GET request is typically used to retrieve data from the server, such as .html
files, images, or JSON data.

■ POST: POST requests are used when sending data to the server, such as adding an item
to a shopping cart or submitting a web form.

■ AJAX: Asynchronous JavaScript and XML (AJAX) is actually just a GET or POST request
that is done directly by JavaScript running in the browser. Despite the name, an AJAX
request can receive XML, JSON, or raw data in the response.
Rendering the Browser View
The screen that the user actually views and interacts with is often made up of several
different pieces of data retrieved from the webserver.
The browser reads data from the initial URL and then renders the HTML document to build
a Document Object Model (DOM). The DOM is a tree structure object with the HTML
document as the root. The structure of the tree basically matches the structure of the HTML
document. For example, document will have html as a child, and html will have head and
body as children, and body may have div , p , or other elements as children, like this:
document
+ html
+ head
+ body
+ div
+p
Rendering the Browser View
The browser interprets each DOM element and renders it to the user’s screen to build the
webpage view. The browser often gets various types of data from multiple webserver
requests to build a webpage.

The following are the most common types of data the browser uses to render the final user
view as well as define the webpage behavior:
■ HTML files: These provide the fundamental structure of the DOM.
■ CSS files: These define how each of the elements on the page is to be styled, in terms of
font, color, borders, and spacing.
■ Client-side scripts: These are typically JavaScript files. They can provide added
functionality to a webpage, manipulate the DOM to change the look of the webpage, and
provide any necessary logic required to display the page and provide functionality.
■ Media files: Image, video, and sound files are rendered as part of the webpage.
Data: Data such as XML, JSON, or raw text can be provided by the webserver as a
response to an AJAX request. Rather than send a request back to the server to rebuild
the webpage, new data can be retrieved via AJAX and inserted into the webpage via
JavaScript.
■ HTTP headers: HTTP defines a set of headers that the browser can use and client-side
scripts to define the behavior of the webpage. For example, cookies are contained in the
HTTP headers. The HTTP headers also define the type of data in the request as well as the
type of data expected to be returned to the browser.

User Interaction
The user interacts with the browser via mice, keyboards, and touchscreens. A browser has
an elaborate event system that captures user input events and then takes the appropriate
actions.
Actions vary from displaying a popup menu to loading a new document from the server to
executing client-side JavaScript.
Webservers
A webserver’s main focus is handling requests from browsers. As described earlier, a browser
may request a document, post data, or perform an AJAX request to get data. The webserver
uses HTTP headers as well as a URL to determine what action to take. This is where things
get very different, depending on the webserver, configuration, and technologies used.
Most out-of-the-box webservers such as Apache and IIS are made to serve static files such
as .html, .css, and media files. To handle POST requests that modify server data and AJAX
requests to interact with backend services, webservers need to be extended with server-side
scripts.
A server-side script is really anything that a webserver can execute in order to perform the
task the browser is requesting. These scripts can be written in PHP, Python, C, C++, C#, Perl,
Java, ... the list goes on and on. Webservers such as Apache and IIS provide mechanisms to
include server-side scripts and then wire them up to specific URL locations requested by the
browser.
This is where having a solid webserver framework can make a big difference. It often takes
quite a bit of configuration to enable various scripting languages and wire up the server-side
scripts so that the webserver can route the appropriate requests to the appropriate scripts.
Server-side scripts either generate a response directly by executing their code or connect with
other backend servers such as databases to obtain the necessary information and then use
that information to build and send the appropriate responses.
Backend Services
Backend services are services that run behind a webserver and provide data that is used to
build responses to the browser. The most common type of backend service is a database
that stores information. When a request comes in from the browser that requires
information from the database or other backend service, the server-side script connects to
the database, retrieves the information, formats it, and then sends it back to the browser.
On the other hand, when data comes in from a web request that needs to be stored in the
database, the server-side script connects to the database and updates the data.
MERN Stack
MERN is a pre-built technology stack based on JavaScript technologies.
MERN stands for MongoDB, Express, React, and Node, after the four key technologies
that make up the stack.

MongoDB — document database


Express(.js) — Node.js web framework
React(.js) — a client-side JavaScript framework
Node(.js) — the premier JavaScript web server (runtime)

Express and Node make up the middle (application) tier.


Express.js is a server-side web framework, and Node.js is the popular and powerful
JavaScript server platform.
The MERN architecture allows you to easily construct a three-tier architecture (front end,
back end, database) entirely using JavaScript and JSON.
React.Js Front End
The top tier of the MERN stack is React.js, the declarative JavaScript framework for creating dynamic client-side
applications in HTML. React lets you build complex interfaces through simple components, connect them to data on
your back-end server, and render them as HTML.
React's strong suit is handling stateful, data-driven interfaces with minimal code and hassle, and it has all the
features you'd expect from a modern web framework: great support for forms, error handling, events, lists, and
more.

Express.Js And Node.Js Server Tier


The next level down is the Express.js server-side framework, running inside a Node.js server. Express.js bills itself
as a “fast, unopinionated, minimalist web framework for Node.js,” and that is indeed exactly what it is. Express.js
has powerful models for URL routing (matching an incoming URL with a server function), and handling HTTP
requests and responses.
By making XML HTTP Requests (XHRs), GETs, or POSTs from your React.js front end, you can connect to
Express.js functions that power your application. Those functions, in turn, use MongoDB's Node.js drivers, to access
and update data in your MongoDB database.

Mongodb Database Tier


If your application stores any data (user profiles, content, comments, uploads, events, etc.), then you're going to
want a database that's just as easy to work with as React, Express , and Node.js.

That's where MongoDB comes in: JSON documents created in your React.js front end can be sent to the Express.js
server, where they can be processed and (assuming they're valid) stored directly in MongoDB for later retrieval.
MEAN stack

The MEAN stack is a JavaScript-based framework for developing scalable web


applications.
The term MEAN is an acronym for MongoDB, Express, Angular, and Node — the four
key technologies that make up the layers of the technology stack.

MongoDB: A NoSQL, object-oriented database designed for use with cloud applications
Express(.js): A web application framework for Node(.js) that supports interactions between
the front end (e.g., the client side) and the database
Angular(.js): Often referred to as the “front end"; a client-side JavaScript framework used
to create dynamic web applications to work with interactive user interfaces
Node(.js): The premier JavaScript web server used to build scalable network applications
MEAN Vs MERN

Aspect MEAN (Angular) MERN (React)


Frontend Framework Angular React
Steeper, due to Angular Easier, React is more
Learning Curve
complexity lightweight
Data Binding Two-Way Binding One-Way Binding
Slightly slower for simple
Performance Faster for dynamic UIs
apps
Preferred for startup and
Popularity Preferred for enterprise apps
medium-sized projects
Strong (Meta/Facebook-
Community Support Strong (Google-backed)
backed)
Full Stack
A full-stack developer works on both the front end and back end of an application. The full-
stack developer has expertise in all phases of development, from user interfaces to
databases and server management.

Components of Full Stack


Front End - Technologies like HTML, CSS, and JavaScript frameworks (React, Angular,
Vue.js).
Back End - Server-side languages (Node.js, Java, Python) and frameworks (Express.js,
Django).
Database - Various databases like SQL (MySQL, PostgreSQL) or NoSQL (MongoDB).
Server - Deployment platforms and server management tools.
Key Features of Full Stack
Full-stack developers can work on all aspects of an application, making them highly
versatile.
They can handle everything from designing the user interface to managing databases and
server logic.
They possess a broad understanding of various technologies and can address complex
issues.
Pros for Full Stack
Full-stack developers are well-versed in all areas of web development.
Ability to work with various technologies and stacks.
Cons for Full Stack
Full-stack developers may not have the same level of specialization in specific technologies
as experts in those fields.
Managing both the front end and back end can be overwhelming, particularly in large
projects.
MEAN Stack MERN Stack Full Stack
The Components of Full Stack are the
The Components of MEAN Stack are MongoDB, The Components of MERN Stack are MongoDB,
combinations of front-end, back-end and
Express.js, Angular, Node.js Express.js, React, Node.js
database.

The frontend framework for MEAN stack is The frontend framework for the MERN stack is The frontend framework for the full stack can be
Angular React Angular, React, or Vue.js.

The backend framework for the MEAN stack is The backend framework for the MERN stack is The backend framework for full stack can be
Express.js Express.js Express.js, Django, and Spring Boot.

The database for the full stack can be chosen


The database for the MEAN stack is MongoDB The database for the MERN stack is MongoDB
any one from MongoDB and SQL databases.

It uses JavaScript as primary language for The MERN stack primary language is The full-stack primary language can be Java or
front-end and back-end JavaScript (for both front-end and back-end) Javascript or Python.

It depends on the chosen front-end framework


It uses two-way data binding with Angular It uses one-way data binding with React such as Angular for two-way binding and React
for one-way binding.

It is Moderate; Angular has a steeper learning


It is Moderate; React is simpler than Angular This varies based on the technologies used
curve
It depends on the chosen stack; often MVC or
It is based on MVC (Model-View-Controller) It is based on Component-based architecture
similar

In full stack, the popularity depends on specific


Angular is less popular than React React is highly popular for front-end
technologies used

Angular’s two-way data binding can be less React’s virtual DOM often offers better The performance varies widely with stack choice
effective performance and optimization; stacks may optimize differently
Understanding the Node.js-to-AngularJS Stack Components
• The most common and the best version of this stack is the Node.js-to-AngularJS stack
comprised of MongoDB, Express, AngularJS, and Node.js.
• In the Node.js-to-AngularJS stack, Node.js provides the fundamental platform for
development.
• The backend services and server-side scripts are all written in Node.js.
• MongoDB provides the data store for the website but is accessed via a MongoDB driver
Node.js module.
• The webserver is defined by Express, which is also a Node.js module.
• The view in the browser is defined and controlled using the AngularJS framework.
AngularJS is an MVC framework in which the model is made up of JSON or JavaScript
objects, the view is HTML/CSS, and the controller is AngularJS JavaScript code.
• Figure 1.2 provides a very basic diagram of how the Node.js to AngularJS stack fits into
the basic website/web application model.
• The following sections describe each of these technologies and why they were chosen as
part of the Node.js to AngularJS stack.
Basic diagram showing where Node.js, Express, MongoDB, and AngularJS fit in the
web paradigm
Node.js
• Node.js is a development framework that is based on Google’s V8 JavaScript engine and executes it.
• You can write most—or maybe even all—of your server-side code in Node.js, including the webserver and the
server-side scripts and any supporting web application functionality.
• The fact that the webserver and the supporting web application scripts are running together in the same
server-side application allows for much tighter integration between the webserver and the scripts.
• Also, the webserver can run directly on the Node.js platform as a Node.js module, which means it’s much
easier than using, say, Apache for wiring up new services or server-side scripts.
The following are just a few reasons Node.js is a great framework:
• JavaScript end-to-end: One of the biggest advantages of Node.js is that it allows you to write both server-
and client-side scripts in JavaScript. There have always been difficulties in deciding whether to put logic in
client-side scripts or server-side scripts. With Node.js you can take JavaScript written on the client and easily
adapt it for the server and vice versa. An added plus is that client developers and server developers are
speaking the same language.
• Event-driven scalability: Node.js applies a unique logic to handling web requests. Rather than having
multiple threads waiting to process web requests, with Node.js they are processed on the same thread, using
a basic event model. This allows Node.js webservers to scale in ways that traditional webservers can’t.
• Extensibility: Node.js has a great following and very active development community. People are providing
new modules to extend Node.js functionality all the time. Also, it is very simple to install and include new
modules in Node.js; you can extend a Node.js project to include new functionality in minutes.
• Fast implementation: Setting up Node.js and developing in it are super easy. In only a few minutes you can
install Node.js and have a working webserver.
MongoDB
• MongoDB is an agile and very scalable NoSQL database.
• The name Mongo comes from the word “hu mongo us,” emphasizing the scalability and
performance MongoDB provides.
• It is based on the NoSQL document store model, which means data is stored in the
database as basically JSON objects rather than as the traditional columns and rows of a
relational database.
• MongoDB provides great website backend storage for high-traffic websites that need to
store data such as user comments, blogs, or other items because it is quickly scalable
and easy to implement.
Node.js supports a variety of database access drivers, so the data store can easily be
MySQL or some other database. However, the following are some of the reasons that
MongoDB really fits in the Node.js stack well:
■ Document orientation: Because MongoDB is document oriented, data is stored in the
database in a format that is very close to what you deal with in both server-side and client-
side scripts. This eliminates the need to transfer data from rows to objects and back.
■ High performance: MongoDB is one of the highest-performing databases available.
Especially today, with more and more people interacting with websites, it is important to
have a backend that can support heavy traffic.
■ High availability: MongoDB’s replication model makes it very easy to maintain scalability
while keeping high performance.
■ High scalability: MongoDB’s structure makes it easy to scale horizontally by sharding
the data across multiple servers.
Express
• The Express module acts as the webserver in the Node.js-to-AngularJS stack. Because it
runs in Node.js, it is easy to configure, implement, and control.
• The Express module extends Node.js to provide several key components for handling web
requests. It allows you to implement a running webserver in Node.js with only a few lines of
code.
• For example, the Express module provides the ability to easily set up destination routes
(URLs) for users to connect to. It also provides great functionality in terms of working with
HTTP request and response objects, including things like cookies and HTTP headers.
• The following is a partial list of the valuable features of Express:
• Route management: Express makes it easy to define routes (URL endpoints) that tie
directly to the Node.js script functionality on the server.
• Error handling: Express provides built-in error handling for “document not found” and
other errors.
• Easy integration: An Express server can easily be implemented behind an existing
reverse proxy system, such as Nginx or Varnish. This allows you to easily integrate it into
your existing secured system.
• Cookies: Express provides easy cookie management.
• Session and cache management: Express also enables session management and
cache management.
AngularJS
• AngularJS is a client-side framework developed by Google.
• It provides all the functionality needed to handle user input in the browser, manipulate data on the client side,
and control how elements are displayed in the browser view.
• It is written in JavaScript, with a reduced jQuery library.
• The theory behind AngularJS is to provide a framework that makes it easy to implement web applications
using the MVC framework.
• Other JavaScript frameworks could be used with the Node.js platform, such as Backbone, Ember, and Meteor.
• However, AngularJS has the best design, feature set, and trajectory at this writing.
• Here are some of the benefits AngularJS provides:
1. Data binding: AngularJS has a very clean method for binding data to HTML elements, using its powerful
scope mechanism.
2. Extensibility: The AngularJS architecture allows you to easily extend almost every aspect of the language to
provide your own custom implementations.
3. Clean: AngularJS forces you to write clean, logical code.
4. Reusable code: The combination of extensibility and clean code makes it very easy to write reusable code in
AngularJS. In fact, the language often forces you to do so when creating custom services.
5. Support: Google is investing a lot into this project, which gives it an advantage over similar initiatives that
have failed.
6. Compatibility: AngularJS is based on JavaScript and has a close relationship with jQuery.
• This makes it easier to begin integrating AngularJS into your environment and reuse pieces of your existing
code within the structure of the AngularJS framework.
JavaScript

• JavaScript was initially created to “make web pages alive”.


• The programs in this language are called scripts. They can be written right in a web
page’s HTML and run automatically as the page loads.
• Scripts are provided and executed as plain text. They don’t need special preparation or
compilation to run.
• Today, JavaScript can execute not only in the browser, but also on the server, or actually
on any device that has a special program called the JavaScript engine.
• The browser has an embedded engine sometimes called a “JavaScript virtual machine”.
• Different engines have different “codenames”.
• For example:
• V8 – in Chrome, Opera and Edge.
• SpiderMonkey – in Firefox.
• “Chakra” for IE,
• “JavaScriptCore”, “Nitro” and “SquirrelFish” for Safari, etc.
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().

The example below "finds" an HTML element (with id=“b"), and changes the element content
(innerHTML) to “My first JavaScript":

<html>
<body>
<h2>What Can JavaScript Do?</h2>

<p id="b">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("b").innerHTML = "My first JavaScript!“’>


Click Here! </button>

</body>
</html>
JavaScript Can Change HTML Content
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id=“B1">First Line of JavaScript.</p>
<p id=“B2">Second Line of JavaScript.</p>

<button type="button"
onclick='document.getElementById(“B1").innerHTML =
"Changed First Line JavaScript!"'>Click Here
First!</button>

<button type="button"
onclick='document.getElementById(“B2").innerHTML =
"Changed Second Line JavaScript!"'>Click Here
Second!</button>

</body>
</html>
JavaScript can change the style, can hide and show
hidden elements
<html><body>
<p id="b1">JavaScript can change the style of an HTML
element.</p>
<button type="button"
onclick="document.getElementById('b1').style.fontSize='35
px'">Click First!</button>

<p id="b2">JavaScript can hide HTML elements.</p>


<button type="button"
onclick="document.getElementById('b2').style.display='non
e'">Click Second!</button>

<p>JavaScript can show hidden HTML elements.</p>


<p id="b3" style="display:none">Hello JavaScript!</p>
<button type="button"
onclick="document.getElementById('b3').style.display='blo
ck'">Click Third!</button> </body> </html>
Understanding Node.js
• Node.js was developed in 2009 by Ryan Dahl as an answer to the frustration caused
by concurrency issues, especially when dealing with web services.
• Google had just come out with the V8 JavaScript engine for the Chrome web browser,
which was highly optimized for web traffic.
• Dahl created Node.js on top of V8 as a server-side environment that matched the
client-side environment in the browser.
• The result is an extremely scalable server-side environment that allows developers to
more easily bridge the gap between client and server.
• The fact that Node.js is written in JavaScript allows developers to easily navigate back
and forth between client and server code and even reuse code between the two
environments.
• The Node.js environment is clean and easy to install, configure, and deploy.
Who Uses Node.js?
• Node.js quickly gained popularity among a wide variety of companies.
• These companies use Node.js first and foremost for scalability but also for ease of
maintenance and faster development.
• The following are just a few of the companies using the Node.js technology:
■ Yahoo!
■ LinkedIn
■ eBay
■ New York Times
■ Dow Jones
■ Microsoft
■ Netflix
■ NASA
■ Trello
■ PayPal
■ Walmart
■ Uber
■ Twitter
■ GoDaddy
What Is Node.js Used For?
Node.js can be used for a wide variety of purposes. Because it is based on V8 and has
highly optimized code to handle HTTP traffic, the most common use is as a webserver.
However,Node.js can also be used for a variety of other web services such as:
■ Web services APIs such as REST
■ Real-time multiplayer games
■ Backend web services such as cross-domain, server-side requests
■ Web-based applications
■ Multiclient communication such as IM
What Does Node.js Come With?
Node.js comes with many built-in modules available right out of the box.

■ Assertion testing: Allows you to test functionality within your code.


■ Buffer: Enables interaction with TCP streams and file system operations.
■ C/C++ add-ons: Allows for C or C++ code to be used just like any other Node.js module.
■ Child processes: Allows you to create child processes.
■ Cluster: Enables the use of multicore systems.
■ Command line options: Gives you Node.js commands to use from a terminal.
■ Console: Gives the user a debugging console.
■ Crypto: Allows for the creation of custom encryption
■ Debugger: Allows debugging of a Node.js file.
■ DNS: Allows connections to DNS servers.
■ Errors: Allows for the handling of errors.
■ Events: Enables the handling of asynchronous events.
■ File system: Allows for file I/O with both synchronous and asynchronous methods.
■ Globals: Makes frequently used modules available without having to include them first.
■ HTTP: Enables support for many HTTP features.
■ HTTPS: Enables HTTP over the TLS/SSL.
■ Modules: Provides the module loading system for Node.js.
■ Net: Allows the creation of servers and clients.
■ OS: Allows access to the operating system that Node.js is running on.
■ Path: Enables access to file and directory paths.
■ Process: Provides information and allows control over the current Node.js process.
■ Query strings: Allows for parsing and formatting URL queries.
■ Readline: Enables an interface to read from a data stream.
■ REPL: Allows developers to create a command shell.
■ Stream: Provides an API to build objects with the stream interface.
■ String decoder: Provides an API to decode buffer objects into strings.
■ Timers: Allows for scheduling functions to be called in the future.
■ TLS/SSL: Implements TLS and SSL protocols.
■ URL: Enables URL resolution and parsing.
■ Utilities: Provides support for various apps and modules.
■ V8: Exposes APIs for the Node.js version of V8.
■ VM: Allows for a V8 virtual machine to run and compile code.
■ ZLIB: Enables compression using Gzip and Deflate/Inflate.
Installing Node.js
• To easily install Node.js, download an installer from the Node.js website at http://
nodejs.org.
• The Node.js installer installs the necessary files on your PC to get Node.js up and
running.
• No additional configuration is necessary to start creating Node.js applications.
• Looking at the Node.js Install Location If you look at the install location, you will see a
couple of executable files and a node_modules folder.
• The node executable file starts the Node.js JavaScript VM.
• The following list describes the executables in the Node.js install location that you need to
get started:
■ node: This file starts a Node.js JavaScript VM. If you pass in a JavaScript file
location, Node.js executes that script. If no target JavaScript file is specified, then a
script prompt is shown that allows you to execute JavaScript code directly from the
console.
■ npm: This command is used to manage the Node.js packages.
■ node_modules: This folder contains the installed Node.js packages. These
packages act as libraries that extend the capabilities of Node.js.
Download nodejs: https://nodejs.org

Download Visual Studio: https://code.visualstudio.com


Select Terminal in VS code
Visual Studio

First Program “Hello World”


Program using Variables
Using Built-in Modules

var http = require('http’);//To include a module, use the require() function with the name of the
module
http.createServer(function (req, res) {// Create an HTTP server
// Write the HTTP response header
// Status code 200 indicates success
// 'Content-Type': 'text/html' specifies the content type of the response
res.writeHead(200, {'Content-Type': 'text/html’});
res.end('Hello World!');
}).listen(8080);

Note: if 8080 is already in use and running you will get error. Change it. By default 3000 is
used in the Node.js
Create Your Own Modules
You can create your own modules and easily include them in your applications.

datetime.js datetimecall.js
var http = require('http’);
Use the exports keyword to make // Import a custom module named 'datej'
properties and methods available var dt = require('./datej');
outside the module file.
http.createServer(function (req, res) {
exports.myDateTime = res.writeHead(200, {'Content-Type':
function () { 'text/html'});
return Date(); res.write("The date and time are
}; currently: " + dt.myDateTime());
res.end();
}).listen(8080);
Read the Query String
The function passed into the http.createServer() has a req argument that represents the
request from the client, as an object

var http = require('http');


http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(req.url);
res.end();
}).listen(8080);
Package
A package in Node.js contains all the files you need for a module.
Modules are JavaScript libraries you can include in your project.

Download a Package
Downloading a package is very easy.
Open the command line interface and tell NPM to download the package you want.

Command Prompt
Using a Package

var http = require('http’);

var uc = require('upper-case’);

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});

res.write(uc.upperCase("Hello World!"));

res.end();
}).listen(8080);
Creating user defined modules and fuctions

calj.js
calci.js
function add(a,b){
return a+b var calj = require('./calj');
}
exports.add = add result=calj.add(5,7)
console.log("The output is = "+result)
function sub(a,b){
return a-b result=calj.sub(7,5)
} console.log("The output is = "+result)
exports.sub = sub
Working with Node Packages
One of the most powerful features of the Node.js framework is the ability to easily extend it
with additional Node Packaged Modules (NPMs) using the Node Package Manager
(NPM).
A Node Packaged Module is a packaged library that can easily be shared, reused, and
installed in different projects.
Many different modules are available for a variety of purposes.
For example, the
Mongoose module provides an ODM (Operational Data Model) for MongoDB,
Express extends Node’s HTTP capabilities, and so on.

Node.js modules are created by various third-party organizations to provide the needed
features that Node.js lacks out of the box.
Node Packaged Modules include a package.json file that defines the packages.
The package.json file includes informational metadata, such as the name, version author,
and contributors, as well as control metadata, such as dependencies and other
requirements that the Node Package Manager uses when performing actions such as
installation and publishing.

Understanding the Node Package Registry


The Node modules have a managed location called the Node Package Registry where
packages are registered.
This allows you to publish your own packages in a location where others can use them as
well as download packages that others have created.
Using the Node Package Manager

The Node Package Manager allows you to find, install, remove, publish, and do everything
else related to Node Package Modules.

The Node Package Manager provides the link between the Node Package Registry and
your development environment.
npm command-line options (with express as the package, where appropriate)
Understanding the Node Package Registry

The Node Package Registry is located at https://npmjs.com.


From this location you can view the newest and most popular modules as well as search for
specific packages.
Installing Node Packaged Modules

Command Prompt
Directives used in the package.json file
Directives used in the package.json file
• A great way to use package.json files is to automatically download and install the dependencies for
your Node.js app. All you need to do is create a package.json file in the root of your project code
and add the necessary dependencies to it. For example, the following package.
• json requires the express module as a dependency.
{
"name": "my_module",
"version": "0.1.0",
"dependencies" : {
"express" : "latest"
}
}
• Then you run the following command from root of your package, and the express module is
automatically installed.
• npm install
• Notice that no module is specified in the npm install.
• That is because npm looks for a package.json file by default.
• Later, as you need additional modules, all you need to do is add those to the dependencies
directive and then run npm install again.

You might also like