Full Stack Unit-I
Full Stack Unit-I
Introduction to Full Stack Development: Understanding the Basic Web Development Framework-
User, Browser, Webserver, Backend Services,
Full Stack Components - Node.js, MongoDB, Express, React, Angular. Java Script Fundamentals,
NodeJS- Understanding Node.js, Installing Node.js, Working with Node Packages, creating a
Node.js Application, Understanding the Node.js Event Model, Adding Work to the Event Queue,
Implementing Callbacks.
Full stack development:
Full Stack Development refers to the development of both front end (client side) and back
end (server side) portions of web applications.
full Stack Web Developers
Full Stack web developers have the ability to design complete web applications and websites. They
work on the frontend, backend, database, and debugging of web applications or websites.
To get you in the right mind-set to understand the benefits of utilizing Node.js, MongoDB, and
AngularJS as your web framework, this section provides an overview of the basic components of
most websites. If you are already familiar with the full web framework, then this section will be old
hat, but if you only understand just the server side or client side of the web framework, then this
section will give you a more complete picture.
The main components of any web framework are the user, browser, webserver, and backend
services. Although websites vary greatly in terms of appearance and behavior, all have these basic
components in one form or another.
This section is not intended to be in-depth, comprehensive, or technically exact but rather a very
high-level perspective of the parts involved in a functional website. The components are described
in a top-down manner, from user down to backend services. Then the next section discusses the
Node.js-to-AngularJS stack from the bottom up, so you can get a picture of where each of the pieces
fits and why. Figure 1.1 provides a basic diagram to help you visualize the components in a
website/web application, which are discussed in the following sections.
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
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:
Figure 1.2 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
“humongous,” 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.
This book covers using the MongoDB driver library to access MongoDB from Node.js.
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:
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:
Data binding: AngularJS has a very clean method for binding data to HTML elements,
using its powerful scope mechanism.
Extensibility: The AngularJS architecture allows you to easily extend almost every
aspect of the language to provide your own custom implementations.
Clean: AngularJS forces you to write clean, logical code.
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.
Support: Google is investing a lot into this project, which gives it an advantage over
similar initiatives that have failed.
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 is a powerful language with a rich set of features that enable developers to create dynamic and
interactive web applications. Understanding its fundamentals is essential for anyone looking to work in web
development.
JavaScript programs can be inserted almost anywhere into an HTML document
using the <script> tag.
For instance:
<!DOCTYPE HTML>
<html>
<body>
<p>Before the script...</p>
<script>
alert( 'Hello, world!' );
</script>
<p>...After the script.</p>
</body>
</html>
javascript
Copy code
var name = "John";
let age = 30;
const isStudent = true;
Data Types: Common data types include strings, numbers, booleans, null, undefined,
objects, and arrays.
javascript
Copy code
let message = "Hello, World!"; // String
let count = 42; // Number
let isActive = true; // Boolean
let student = null; // Null
let course; // Undefined
2. Operators
Arithmetic Operators: +, -, *, /, %
javascript
Copy code
let sum = 10 + 5; // 15
let product = 10 * 5; // 50
Comparison Operators: ==, ===, !=, !==, <, >, <=, >=
javascript
Copy code
let isEqual = (5 == '5'); // true
let isStrictEqual = (5 === '5'); // false
javascript
Copy code
let result = (true && false); // false
let isNotTrue = !true; // false
3. Control Structures
javascript
Copy code
if (age > 18) {
console.log("Adult");
} else {
console.log("Minor");
}
javascript
Copy code
for (let i = 0; i < 5; i++) {
console.log(i);
}
4. Functions
Function Declaration
javascript
Copy code
function greet(name) {
return "Hello, " + name;
}
Function Expression
javascript
Copy code
const greet = function(name) {
return "Hello, " + name;
};
Arrow Functions
javascript
Copy code
const greet = (name) => "Hello, " + name;
javascript
Copy code
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
console.log(person.firstName); // John
javascript
Copy code
let numbers = [1, 2, 3, 4, 5];
console.log(numbers[0]); // 1
6. DOM Manipulation
JavaScript can interact with and manipulate the HTML DOM (Document Object Model).
javascript
Copy code
document.getElementById("myElement").innerHTML = "New Content";
7. Events
javascript
Copy code
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
8. Asynchronous JavaScript
Callbacks
javascript
Copy code
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 2000);
}
fetchData((data) => {
console.log(data);
});
Promises
javascript
Copy code
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Promise resolved");
} else {
reject("Promise rejected");
}
});
promise.then((message) => {
console.log(message);
}).catch((message) => {
console.log(message);
});
Async/Await
javascript
Copy code
async function fetchData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
}
fetchData();
Understanding Node.js
Node.js is a runtime environment that allows you to run JavaScript code on the server side. It uses
the V8 JavaScript engine (the same one used by Google Chrome) to execute code, and it provides a
non-blocking, event-driven architecture for building scalable network applications.
Installing Node.js
1. Download Node.js:
o Visit the official Node.js website.
o Download the installer for your operating system (Windows, macOS, Linux).
2. Install Node.js:
o Run the installer and follow the instructions.
o Verify the installation by opening a terminal or command prompt and typing:
bash
Copy code
node -v
npm -v
This should display the installed versions of Node.js and npm (Node Package
Manager).
Node.js uses npm to manage packages (libraries and tools). With npm, you can install, update, and
remove packages easily.
1. Initialize a Project:
o Create a new directory for your project and navigate into it.
bash
Copy code
mkdir my-node-app
cd my-node-app
bash
Copy code
npm init -y
This creates a package.json file in your project directory, which keeps track of your
project's dependencies and configuration.
2. Installing Packages:
o Install a package (e.g., Express for web server functionality):
bash
Copy code
npm install express
javascript
Copy code
const express = require('express');
javascript
Copy code
const express = require('express');
const app = express();
2. Define Routes:
o Set up a simple route to handle requests:
javascript
Copy code
app.get('/', (req, res) => {
res.send('Hello, World!');
});
javascript
Copy code
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
bash
Copy code
node app.js
Node.js uses an event-driven model, where events trigger callback functions. This model is
implemented using an event loop, which continuously checks for new events and executes their
corresponding callbacks.
You can use functions like setTimeout, setInterval, and process.nextTick to add tasks to the
event queue.
setTimeout:
javascript
Copy code
setTimeout(() => {
console.log('This will run after 1 second');
}, 1000);
setInterval:
javascript
Copy code
setInterval(() => {
console.log('This will run every 2 seconds');
}, 2000);
process.nextTick:
javascript
Copy code
process.nextTick(() => {
console.log('This will run at the end of the current operation');
});
Implementing Callbacks
Callbacks are functions passed as arguments to other functions and are invoked after the completion
of certain tasks.
javascript
Copy code
function greet(name, callback) {
console.log(`Hello, ${name}!`);
callback();
}
function afterGreet() {
console.log('This function runs after the greet function');
}
greet('John', afterGreet);
javascript
Copy code
const fs = require('fs');
In this example, fs.readFile reads a file asynchronously, and the callback function is executed
after the file reading is complete.