Hi, I'm Shiva Gautam. With over 15 years of diverse experience in various IT domains, I am now an entrepreneur focusing on both training and software development.
My expertise spans across multiple technologies, and I've authored numerous articles on subjects including Java, Python, REACT, NODE, ANGULAR, Cloud, software testing, Django framework, C#, Flutter, Salesforce, Ruby on Rails, .NET, and more.
For additional information, please visit shivaconceptsolution.com and kangaroosoftware.net.
Search This Blog
NODE JS Complete Tutorial | Practical explanation by Shiva Sir
NODE JS Complete Tutorial | Practical explanation by Shiva Sir :
Now a days most of the IT Company asked NODE JS Question mostly in interview.
I am creating this article to provide help to all MERN Stack developer , who want to learn node js easily.
I am Shiva Gautam, I have 15 Years of experience in Multiple IT Technology, I am Founder of Shiva Concept Solution Best Programming Institute with 100% Job placement guarantee.
Node.js is an open-source and cross-platform runtime environment that allows you to use JavaScript to develop server-side applications.
Every web browser has a JavaScript engine that takes JavaScript code and compiles it to machine code. For example, Firefox uses SpiderMonkey, and Google Chrome uses V8. Because browsers use different JavaScript engines, sometimes, you will see that JavaScript behaves differently between browsers.
In 2009, Ryan Dahl, the creator of Node.js, took the V8 engine and embedded it in an application that could execute JavaScript on the server.
Unique Features of NODE JS:-
Node.js is Single-threaded
Node.js is single-threaded. It means that each process has only one thread of execution.
The single-threaded execution model allows Node.js to handle more concurrent requests easily via the event loop. Because of this, Node.js applications typically consume comparatively less memory.
If you have not familiar with the event loop, check out this event loop tutorial. The event loop in Node.js works the same as the event loop in web browsers.
Node.js uses Non-blocking I/O
I/O stands for input/output. It can be disk access, a network request, or a database connection. I/O requests are expensive and slow and hence block other operations.
Node.js addresses blocking I/O issues by using non-blocking I/O requests.
Non-blocking means that you can make a request while doing something else, and then, when this request is finished, a callback will execute to handle the result.
In other words, the program execution can continue while other operations are taking place.
How to Install Node JS:-
Just write the download node in google it provides LTS , and download according to your o/s.
To confirm the installation, you can open Command Prompt or Windows Terminal and type the following command:
node -v
Step to create First Hello World Program in Node JS:-
1) Create Folder
2) Open this folder in VS Code
3) Type npm init
4) create hello.js file
5) write following code
console.log("hello world")
6) open terminal write
node hello.js
What is Modules in NODE JS:-
It is similar to JS library, and it is used to contain predefine functionality under
NODE application.
We can create our own module also.
Node JS provide various modules, we will step all modules one by one
HTTP module in node js:-
This is the most important module to manage HttpRequest and HttpResonse.
Now I am creating one simple program to explain http module.
consthttp = require('http')
consthostname = '127.0.0.1'
constport = 3000
constserver = http.createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/html')
res.end('<h1>Hello World</h1>')
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
Another Example of an HTTP Module:-
consthttp = require('http');
constport = 2000;
consthost = "127.0.0.1"
constserver = http.createServer((req,res)=>{
res.statusCode=200
varp = 120000
varr = 5.5
vart = 2
varsi = (p*r*t)/100
res.setHeader('Content-Type','text/html')
res.end(`<h1>Result is ${si} </h1>`)
})
server.listen(port,host,()=>{
console.log(`click to execute http://${host}:${port}`)
console.log(`Server running at http://${hostname}:${port}/`)
})
The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client. using this we can create web server to post node script under web environment.
Use the createServer() method to create an HTTP server.
Read the query String using Http Module:-
varhttp = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type':'text/html'});
res.write(req.url);
res.end();
}).listen(8080);
File Module in Node JS:-
This is another important module in Node Js that is used to manage file operation.
it provide following operation
1) Write File
2) Read File
3) Append File
4) Delete the File
Node JS provide fs module to perform file handling operation.
varfs = require('fs');
This operation must be implemented using asynchronous mode
Now I am explaining using example:-
varfs = require('fs');
fs.open('abc.txt', 'w', function (err, file) {
if (err) throwerr;
console.log('Saved!');
});
fs.writeFile('abc.txt', 'Hello content!', function (err) {
if (err) throwerr;
console.log('Saved!');
});
fs.readFile('abc.txt',(err, data) => {
vararray = data.toString().split(" ");
console.log(data.toString());
for(iinarray) {
// Printing the response array
console.log(array[i]);
}
})
fs.appendFile('abc.txt', ' dftrdyhtyt.', function (err) {
if (err) throwerr;
console.log('Updated!');
});
fs.unlink('abc.txt', function (err) {
if (err) throwerr;
console.log('File deleted!');
});
fs.rename('abc.txt', 'abcnew.txt', function (err) {
if (err) throwerr;
console.log('File Renamed!');
});
Task for Asynchronous Mode:
First Write then Read
First Read then write
First Append then Read
First Read then append
Create Marksheet program of 12th class student and display result based
console.log('Server running at http://127.0.0.1:1337/');
Event Module in JS:-
This is very simple module that is used to perform the action, we can attach event dynamically using this Event Module.
varevents=require('events');
vareventEmitter=newevents.EventEmitter();
varfun=function(){
console.log("My User Define Event Method");
}
eventEmitter.on('myclick',fun);
eventEmitter.emit('myclick');
User Define Module:-
Using this we can create a custom module that can be used in another file.
Step 1st:-
Create Module:-
exports.mymodule = function () {
return"Welcome in user define module";
};
exports.fun = function () {
return"module fun2";
};
Use Module
constum = require('./mymodule')
console.log(um.mymodule())
console.log(um.fun())
What is Blocking & Non-Blocking of Code?
NODE JS API supports the Non-Blocking of the code, it is a unique feature of the NODE JS Application
and it improves the performance of the NODE Application
Blocking of code means if one process is not completed then another process will be
on hold but in non-blocking features,
if one process takes more time to execute then another process can be completed.
Example of Blocking of Code:-
varfs = require("fs");
vardata = fs.readFileSync('hello.txt');
console.log(data.toString());
console.log("Program Ended");
Example of Non-Blocking of Code:-
varfs = require("fs");
fs.readFile('hello.txt', function (err, data) {
if (err) returnconsole.error(err);
console.log(data.toString());
});
console.log("Program Ended");
What is Stream?
Stream objects that are used to read data from the source and write data into the destination.
there are four types of streams −
Readable − Stream which is used for read operation.
Writable − Stream which is used for write operation.
Duplex − Stream which can be used for both read and write operation.
Transform − A type of duplex stream where the output is computed based on input.
The stream can be connected with Event Emitter instance and user various events to perform the operation
data − This event is fired when there is data is available to read.
end − This event is fired when there is no more data to read.
error − This event is fired when there is any error in receiving or writing data.
finish − This event is fired when all the data has been flushed to underlying system.
What is session and how to store data under session in node js:
Session is server side object that store data permanenly under multiple HttpRequest.
it is used to manage user authentication , and track the information of user after login.
Node js provide express-session library to store session.
npm install express-session
Session store data under db or cookie hence we should use cookie-parser library.
to store data under browser cookie.
npm install cookie-parser
Syntax
const session = require("express-session");
Syntax to store data:
req.session.key = data; (data can be any type)
req.session.save();
Syntax to get data from session
const constname = req.session.key;
Syntax to remove data from session
req.session.destroy();
Q) Code to count total visitor on website using node js and express js api.
const express = require("express");
const session = require("express-session");
const cookieParser = require("cookie-parser");
const PORT = 4000;
const app = express();
app.use(cookieParser());
app.use(session({
secret: "amar",
saveUninitialized: true,
resave: true
}));
app.get('/', (req, res) => {
if (req.session.view) {
req.session.view++;
res.send("You visited this page for "
+ req.session.view + " times");
}
else {
req.session.view = 1;
res.send("You have visited this page"
+ " for first time ! Welcome....");
}
})
app.listen(PORT, () =>
console.log(`Server running at ${PORT}`));
Another code to provide session authentication:
const express = require("express");
const app = express();
const session = require("express-session");
const cookieParser = require("cookie-parser");
const PORT = 4000;
app.use(cookieParser());
app.use(session({
secret: "amar",
saveUninitialized: true,
resave: true
}));
const user = {
name: "Amar",
Roll_number: 43,
Address: "Pune"
};
app.get("/login", (req, res) => {
req.session.user = user;
req.session.save();
return res.send("Your are logged in");
});
app.get("/user", (req, res) => {
const sessionuser = req.session.user;
res.send(sessionuser);
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.send("Your are logged out ");
});
app.listen(PORT, () => console.log(`Server at ${PORT}`));
Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component { constructor ( props ) { super ( props ); this . fun = this . fun . bind ( this ); //event method binding this . input = React . createRef ();...
JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1) inline CSS:- we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2) Internal CSS:- we will write CSS under <style> block. <style type="text/css"> #abc { width:200px; height:100px; background-color:green; } </style> <div id="abc"></div> 3) External CSS:- we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px; height:100px; background-color:green; } go into Jsp page and link style.css <link href="style.css" type="text/css" rel="stylesheet" /> <div id="abc"> </div> Exam...
JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1 Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2 Create Table using database server 3 Create Form according to database table 4 Submit Form and get form data into servlet 5 write JDBC Code:- 5.1) import package import java.sql.* 5.2) Add JDBC Driver according to database ide tools 5.3) call driver in program ...
Comments
Post a Comment
POST Answer of Questions and ASK to Doubt