You are on page 1of 40

What is Node.js?

● Open-source and cross-platform Javascript Runtime Environment


● Runs V8 Javascript Engine, the core of Google Chrome, outside of the
browser,
● Very performant and scalable
● Non-blocking paradigm
● Node.js app runs in a single process without creating a new thread for every
request.
Non-block paradigm means whenever there is an I/O operation like network
access or database request etc., instead of blocking the thread and wasting
CPU cycles, Node.js will resume the operations when the response comes
back
Differences between Node.js and the Browser
Node.js Browser

Both front-end and back-end can be programmed. Javascript is mostly used for manipulating DOM,
accessing cookies etc.

Objects like document, window and all the other objects APIs and modules, like the filesystem access functionality
that are provided by the browser are not present. are not present.

Node.js you control the environment as it runs on server Remote users may use different versions of browsers due
side. to which the functionality may differ.

You can write all the modern ES2015+ JavaScript that Browsers can be a bit slow to upgrade, sometimes on the
your Node.js web you are stuck with using older JavaScript /
ECMAScript releases

Node.js supports both the CommonJS and ES module Browsers are starting to see the ES Modules standard
systems. being implemented.
Installing Node.js
Checking Node.js installation

REPL stands for Read Eval Print Loop


Running a script from a file
helloworld.js

var msg="Hello World";

console.log(msg);
Building an HTTP Server
Build an HTTP Server
const http = require('http')

const hostname = '127.0.0.1' //local machine, this computer


const port = 8080 //port number where the server will receive requests

function sayHello(req,res)
{
res.statusCode = 200 //200 means success
res.setHeader('Content-Type', 'text/plain') //set up the response headers
res.write("Hello World")
res.end() //response packet will be sent back to the browser
}

const server = http.createServer(sayHello) //name of the function to be executed when


the server receives any request

//set the server to start listening to the requests


server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
Output

On Console

On Browser Window
Reading file from file system
Reading files from the file system
Files stored locally on server-side can be read into a Node.js program.
The program can then process the file or send it to the client.

fs module is required to read or write files to the file system

There are two ways to read files in Node.js


- Synchronous
- Asynchronous
Reading files (Synchronously)
Use the method fs.readFileSync to read the file in a synchronous manner.

The control flow shall remain blocked until all file data has been read from
filesystem (file storage).

SYNTAX:

fs.readFileSync(filepath,encoding)
Assume a HTML file stored on server-side
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>About India</title>
</head>
<body>
India, officially the Republic of India is a country in South Asia. It is the
seventh-largest country by area, the second-most populous country, and the most populous
democracy in the world. Bounded by the Indian Ocean on the south, the Arabian Sea on the
southwest, and the Bay of Bengal on the southeast, it shares land borders with Pakistan to
the west;[f] China, Nepal, and Bhutan to the north; and Bangladesh and Myanmar to the east.
In the Indian Ocean, India is in the vicinity of Sri Lanka and the Maldives; its Andaman
and Nicobar Islands share a maritime border with Thailand, Myanmar, and Indonesia. The
nation's capital city is New Delhi.
</body>
</html>
Reading File (Synchronously)
const http = require('http')
const fs = require('fs')

function showPage(req, res) {


try{
const filedata = fs.readFileSync('aboutindia.html','utf8')
res.write(filedata) //writing the file contents into the response body
}
catch(err){
res.write("Some error occurred while reading the file")
}
res.end()
}

const server = http.createServer(showPage)

//start the server


server.listen(3030, '127.0.0.1', () => {
console.log('India Server is now running')
})
Reading files (Asynchronously)
Use the method fs.readFile() method to read the file in asynchronous
manner.
The method will return control immediately after initiating the read operation.
The callback function will be executed once the read operation has been
completed.

SYNTAX:

fs.readfile(filepath,encoding, callbackfunction)
Reading File (Asynchronously)
const http = require('http')
const fs = require('fs')

function showPage(req, res) {


fs.readFile('aboutindia.html', 'utf8',function (err, data) {
if(err)
res.write("Some error occurred while reading the file")
else
res.write(data);
return res.end();
});
}
const server = http.createServer(showPage)

//start the server


server.listen(3030, '127.0.0.1', () => {
console.log('India Server is now running')
})
Exiting from a Node.js program
const http = require('http')
const hostname = '127.0.0.1' //local machine, this computer
const port = 8080 //port number where the server will receive requests

function sayHello(req,res){
res.statusCode = 200 //200 means success
res.setHeader('Content-Type', 'text/plain') //set up the response headers
res.write("Hello World")
res.end() //response packet will be sent back to the browser

//exiting via process.exit


console.log("Server Exiting..I dont bother if previous requests/processes have been
completed.")
process.exit()
}

const server = http.createServer(sayHello)

//set the server to start listening to the requests


server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
1 2

Output on console
const http = require('http')
const hostname = '127.0.0.1' //local machine, this computer
const port = 8080 //port number where the server will receive requests

function sayHello(req,res){
res.statusCode = 200 //200 means success
res.setHeader('Content-Type', 'text/plain') //set up the response headers
res.write("Hello World")
res.end() //response packet will be sent back to the browser
}

const server = http.createServer(sayHello)

//set the server to start listening to the requests


server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})

process.on('SIGTERM',()=>{
server.close(()=>{
console.log("Server Exiting")
})
})
1
3

2 4
ExpressJS
Express is a node js web application framework that provides broad features for
building web and mobile applications. It is used to build a single page, multipage, and
hybrid web application. It's a layer built on the top of the Node js that helps manage
servers and routes.

Installing Express.js module using npm

> npm install express --save


Installing Express.js module using npm

> npm install express --save


“Hello World” Application using ExpressJS
const express = require('express')
const app = express()

app.get('/',(req,res) => {
res.send("Hi!")
})

app.listen(3000,()=>console.log('Server ready'))
Output
ExpressJS: Routing and Handling GET and POST requests
const express = require('express')

const fs = require('fs')

const app = express()

app.get('/',(req,res) => {

res.write('<h1><a href="showsignin">Sign-In</a></h1>')

return res.end();

})

app.listen(3000,()=>console.log('Server ready'))
Contd.

app.get('/showsignin',(req,res) => {

fs.readFile('signin.html', function (err, data) {

res.write(data);

return res.end();

});

})
Contd.
app.post('/dosignin',(req,res) => {
var body = ''
req.on('data', function (data) {
body += data //collecting the request data in the body variable
})
req.on('end', function () {

console.log('Body: ' + body)

var qs = new URLSearchParams(body)

var username = qs.get("username")

var passwd = qs.get('passwd')

if(username == 'tom' && passwd == 'tom123') {

res.write("<h1>Sign-In Successful</h1>")

else {

res.write("<h1>Sign-In Failed</h1>")

res.end()

})

})
Node.js: Connecting to MySQL
MySQL module
Mysql module can be installed using the following command:

> npm install mysql

Include mysql module in your code:

const mysql = require('mysql')


Building the connection object

var con = mysql.createConnection({


host: "localhost", //IP address of the database server
user: "root",
password: "12345678",
database: "it2021"
});
Creating a connection

SYNTAX:
con.connect(callback function to be called when connection is created)

EXAMPLE:
con.connect(function (err) {
if (err) throw err;
//do something
})
Executing a query
SYNTAX:
con.query(query-string, [comma separated query-parameters], callback-function)

EXAMPLE:

con.query("SELECT * FROM user where username=? and passwd=?", [username, passwd],


function (err, result, fields) {
if (err) throw err;

console.log(result);
if (result.length == 1) {
res.write("<h1>Sign-In Successful</h1>")
res.end()
} else {
res.write("<h1>Sign-in Failed</h1>")
res.end()
}
});
Other popular frameworks
● React: A JavaScript library for building user interfaces
● AngularJs: AngularJs is a JavaScript open-source front-end framework that is
mainly used to develop single-page web applications(SPAs). It extends HTML
DOM with additional attributes and makes it more responsive to user actions.
● And many more
Thank You

You might also like