Node JS Presenetation

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 59

NODE.

JS
WHAT IS NODE.JS?
Node.js is a server-side
platform built on Google
Chrome's JavaScript
Engine (V8 Engine).
Node.js was developed by

Ryan Dahl in 2009


WHAT IS NODE.JS?
Node.js is an open source , cross-
platform runtime environment for
developing server-side and networking
applications.
Node.js allows us to run JavaScript on
the server.
Node.js runs on various platforms
(Windows, Linux, Unix, Mac OS X, etc.)
NODE.JS

Node.js =
Runtime Environment
+
JavaScript Library
WHY NODE.JS?
Here is how PHP or ASP handles a file request:
 Sends the task to the computer's file system.

 Waits while the file system opens and reads the file.

 Returns the content to the client.

 Ready to handle the next request.


WHY NODE.JS?
Here is how Node.js handles a file request:
• Sends the task to the computer's file
system.
• Ready to handle the next request.
• When the file system has opened and read
the file, the server returns the content to
the client.
*Node.js eliminates the waiting, and simply continues with the next
request.
*Node.js runs single-threaded, non-blocking, asynchronous
programming, which is very memory efficient.
WHERE TO USE NODE.JS?
Following are the areas where Node.js is
proving itself as a perfect technology partner.
 I/O bound Applications
 Data Streaming Applications
 Data Intensive Real-time Applications (DIRT)
 JSON APIs based Applications
 Single Page Applications
FEATURES OF NODE.JS
 Asynchronous and Event Driven −ll APIs of Node.js
library are asynchronous, that is, non-blocking.
 Very Fast − Being built on Google Chrome's V8

JavaScript Engine, Node.js library is very fast in code


execution.
 Single Threaded but Highly Scalable

 No Buffering − Node.js applications never buffer any

data. These applications simply output the data in


chunks.
 License − Node.js is released under the MIT license
APPLICATIONS OF NODE.JS

Node.js Console
Node.js Web application
CONSOLE BASED
APPLICATION
There are three console methods that
are used to write any node.js stream:
console.log()
console.error()
console.warn()
NODE.JS CONSOLE.LOG()

 The console.log() function is used to display


simple message on console.
 console.log('Hello Welcome to CSE');

 console.log('Hello %s', ‘CSE');

 var dept=“CSE”

 console.log('Hello %s', dept);


 We can also use format specifier in console.log() function.
 File: console_example2.js

var a=10;
var b=15;
console.log(a+b);
console.log(Number(a)+Number(b));
GCD OF TWO NUMBERS
const readVal=require('prompt-sync')();
var num1=readVal("Enter Number-1");
var num2=readVal("Enter number-2");
var res=gcd(num1,num2);
console.log('GCD of '+num1+ ' and '+num2+'
is '+res);
function gcd(n1,n2)
{
if(!n2)
return n1;
else
return (n2,n1%n2);
}
 ode.js console.error()
 The console.error() function is used to render

error message on console.


 File: console_example3.js

 console.error(new Error('Hello! This is a wron

g method.'));
NODE.JS - REPL TERMINAL

 REPL stands for Read Eval Print Loop and it


represents a computer environment like a
Windows console or Unix/Linux shell where a
command is entered and the system responds
with an output in an interactive mode.
 Read − Reads user's input, parses the input

into JavaScript data-structure, and stores in


memory.
 Eval − Takes and evaluates the data

structure.
 Print − Prints the result.

 Loop − Loops the above command until the

user presses ctrl-c twice.


NODE.JS - REPL TERMINAL
 Starting REPL
 REPL can be started by simply

running node on shell/console without any


arguments as follows.
 $ node

 >1 + 3

4 //output
 > 1 + ( 2 * 3 ) - 4

3 //output
 >
USE VARIABLES

 $ node
 > x = 10

10
 > var y = 10

undefined
 > x + y

20
 > console.log("Hello World")

Hello World undefined


MULTILINE EXPRESSION
 $ node
 > var x = 0

 undefined

 > do

 {

 ... x++;

 ... console.log("x: " + x);

 ... }

 while ( x < 5 );

 x: 1 x: 2 x: 3 x: 4 x: 5

 Undefined

 >
UNDERSCORE VARIABLE
YOU CAN USE UNDERSCORE (_) TO GET THE LAST
RESULT −
 $ node
 > var x = 10

 undefined

 > var y = 20

 undefined

> x + y

 30

>

 var sum = _

 undefined

 > console.log(sum)

 30

 Undefined

 >
REPL COMMANDS
 ctrl + c − terminate the current command.
 ctrl + c twice − terminate the Node REPL.

 ctrl + d − terminate the Node REPL.

 Up/Down Keys − see command history and modify

previous commands.
tab Keys − list of current commands.
 .help − list of all commands.

 .break − exit from multiline expression.

 .clear − exit from multiline expression.

 .save filename − save the current Node REPL session

to a file.
 .load filename − load file content in current Node REPL

session.
 node.js console.warn()
 The console.warn() function is used to

display warning message on console.


 File: console_example4.js

 const name = 'John';

 console.warn(`Don't mess with me $

{name}! Don't mess with me!`);


NODE.JS - NPM
Node Package Manager (NPM) provides
two main functionalities −
 Online repositories for node.js

packages/modules which are


searchable on search.nodejs.org
 Command line utility to install Node.js

packages, do version management


and dependency management of
Node.js packages.
 open console and type the following

command to get npm verson


 $npm --version
INSTALLING MODULES USING
NPM
 There is a simple syntax to install any Node.js module

$ npm install <Module Name>
 Example

$ npm install express


$ npm install prompt-sync
 Now you can use these module in your js file as
following –
var express = require('express');
var prompt = require('prompt-sync')();
GLOBAL VS LOCAL INSTALLATION
 By default, NPM installs any dependency in the
local mode. Here local mode refers to the package
installation in node_modules directory lying in the
folder where Node application is present. Locally
deployed packages are accessible via require()
method.
$ npm ls //shows locally installed
 $ ls –l

$ npm install express –g


$ npm ls –g //shoes
globally installed
NODE.JS WEB-BASED EXAMPLE
A node.js web application contains the following three
parts:
Import required modules − We use
the require directive to load Node.js
modules.
Create server − A server which will
listen to client's requests similar to Apache
HTTP Server.
Read request and return response −
The server created in an earlier step will
read the HTTP request made by the client
which can be a browser or a console and
return the response.
STEP-1: IMPORT REQUIRED MODULE
 To create Node.js web application the required
module is “http”.
 Import required module: The first step is to use ?
require? directive to load http module and store
returned HTTP instance into http variable.
For example:

var http = require("http");


 In NodeJS, require() is a built-in function to include
external modules that exist in separate files.
 require() statement basically reads a JavaScript file,
executes it, and then proceeds to return the export
object.
var myVar = require(‘module_name');
//to use built-in modules
var myVar2 = require('./myLocaModule');
//to use local modules
STEP-2: CREATE SERVER
• In the second step, you have to use created http
instance and call http.createServer() method to
create server instance and then bind with some
port number using listen() method associated
with server instance.
createServer():
 This method turns your computer into an HTTP

server.
http.createServer(requestListener);
requestListener:
 Specifies a function to be executed every time the server gets a
request. This function is called a requestListener, and handles request
from the user, as well as response back to the user.
 It is a Call back function, it will be executed once the server is created.
NODE.JS AS A WEB SERVER
• The HTTP module can create an HTTP server that
listens to server ports and gives a response back to
the client.
• Use the createServer() method to create an HTTP
server:
http.createServer(function (req, res)
{
//html code,server code…
}
).listen(portno);
OR
var x=http.createServer(function (req, res)
{
//html code,server code…
}
);
x.listen(port_num);
ADD AN HTTP HEADER
 If the response from the HTTP server is supposed to be
displayed as HTML, you should include an HTTP header
with the correct content type:
 If the response from the HTTP server is supposed to be

displayed as HTML, you should include an HTTP header


with the correct content type:
Syntax:

res.writeHead(Status_code, Response_type);

Status_code: 200 (OK or Success), 404


(Error)
Example:

res.writeHead(200,{‘content-type’:’plain/html’});
STEP-3:WRITE A RESPONSE TO THE
CLIENT USING RESPONSE OBJECT OF
WRITE()
 To add a response to the res object or to display
data on the web browser use res.write() method.
 Syntax:

res.write(“Message”);
Example:
res.write(“Hello”);
res.write(“<h1>welcome</
h1>”);

At last to end the response to client need to


invoke res.end() method.
EXAMPLE1

var http=require('http');
http.createServer(function(req,res)
{

res.writeHead(200,{'content-type':'text/plain'});
res.write("<body bgcolor='pink'>");
res.write("<h1>welcome to Node js</h1>");
res.end();
}).listen(4040);
console.log("Server 4040 started");
EXAMPLE2
var ser=http.createServer(function(req,res){
res.writeHead(200,{‘content-type’:’text/
html’});
res.write(“Hello world”);
res.write(“<br>”);
res.write(“<h1> hi hello</h1>”);
res.end();
});
ser.listen(2020);
WHAT IS MODULARIZATION?

 Modularization is a software design technique in


which the functionality of a program is separated into
independent modules, such that each module
contains the desired functionality.
 Advantages of modularization:
 Readability

 Easier to debug
 Reusable Code
 Reliability
 Node environment provides many built-
in modules that can be used in
application development.
 We have already seen the usage of the

"HTTP" module, which is a built-in


module in Node.js for creating a web
server.
 Node.js also provides many other useful

modules like
 fs module (used for file-related operations)
 os module(used for operating system-related
functions)
 net module( used for socket programming),
etc. for server-side application development.
HOW TO CREATE AND LOAD A
MODULE IN A NODE
APPLICATION.
 Step 1: Create a file module1.js within the
NodeJS folder created earlier
 Program:

exports.findBiggestNumber = (first, second)


=> {
if (first > second)
{
return first;
}
else
return second;
};
 Step-2: create module2.js for loading module1.js
const http = require("http");
var lmodule = require("./module2");
var server = http.createServer((req, res) => {
result = lmodule. findBiggestNumber(220, 100);
res.writeHead(200, { "Content-Type":
"text/html" });
res.write("<html><body><h1> The Biggest
Number of Two Numbers is:" + result +
"</h1></body></html>");
res.end();
console.log("Request received");
});
server.listen(3020);
console.log("Server is running at port 3020");
RESTARTING NODE APPLICATION
 Whenever we are working on a Node.js application
and we do any change in code after the application is
started, we will be required to restart the Node process
for changes to reflect.
 In order to restart the server and to watch for any code

changes automatically, we can use the Nodemon tool.


Nodemon
 Nodemon is a command-line utility that can be executed
from the terminal.
 It provides a different way to start a Node.js application.

 It watches the application and whenever any change is

detected, it restarts the application.


 Step-1: Install nodemon
npm install nodemon –g
 Oncethe 'nodemon' is installed in the
machine, the Node.js server code can be
executed by replacing the command
"node" with "nodemon".
nodemon app.js
 Thusthe 'nodemon' starts the application
in watch mode and restart the application
when any change is detected.
httpserver.js
const http = require("http");
var server = http.createServer((req, res) => {
res.write("Hello World! I have created my first
server!");
res.end();
});
server.listen(3000);
console.log("Server started... Running on
localhost:3000");
 Execution:

Node>nodemon httpserver.js
 Now open the application code and do changes in the
code as below.
const http = require("http");
var server = http.createServer((req, res) => {
res.write("Hello World! I have created my first server!");
res.write("nodemon Example Program!");
res.end();
});
server.listen(3000);
console.log("Server started... Running on
localhost:3000");
Observe the console message in the command
prompt. Nodemon automatically restarted the
server on observing changes in the code.
WHAT IS FS MODULE?
 The fs module provides a wrapper that contains the
standard file operations for manipulating files and
dealing with the computing platform's file system.
 How to use fs module?
 Toinclude the File System module, use the require()
method:
Syntax:
const fs = require('fs');
 File operations are:
 Reading data from a file
 Creating a file
 Writing data to a file
 Updating content in a file
 Delete Files
 Rename Files
READING FILE
const fs = require('fs');
fs.readFile(fileName [,options],
callback)
 filename: Full path and name of the file

as a string.
 options: The options parameter can be

an object or string which can include


encoding and flag. The default encoding is
utf8 and default flag is "r".
 callback: A function with two parameters

err and fd. This will get called when


readFile operation completes.
Exampe:1
var fs = require('fs');
fs.readFile('sample.txt', 'utf8',function (err, data)
{
if (err) throw err;

console.log(data); });
console.log('Open a File to Reading');

Example:2
var fs = require('fs');
var data = fs.readFileSync(‘sample.txt', 'utf8');
console.log(data);
console.log('Open a File to Reading');
Server Application:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res)
{
//Open a file on the server and return its content:
fs.readFile('sample.txt', function(err, data)
{
res.writeHead(200, {'Content-Type':
'text/html'});
res.write("<h1>"+data+"</h1>");
return res.end();
});
}).listen(3030);
CREATING FILE
const fs = require('fs');
fs.open(filename, flags[, mode],
callback)
 filename: Full path and name of the file

as a string.
 Flag: The flag to perform operation

 Mode: The mode for read, write or

readwrite. Defaults to 0666 readwrite.


 callback: A function with two parameters

err and data. This will get called when


readFile operation completes.
Flags
The following table lists all the flags which can be used in read/write operation.

Flag Description
r Open file for reading. An exception occurs if the file does not exist.
r+ Open file for reading and writing. An exception occurs if the file does not
exist.
rs Open file for reading in synchronous mode.
rs+ Open file for reading and writing, telling the OS to open it synchronously.
See notes for 'rs' about using this with caution.
w Open file for writing. The file is created (if it does not exist) or truncated
(if it exists).
wx Like 'w' but fails if path exists.
w+ Open file for reading and writing. The file is created (if it does not exist) or
truncated (if it exists).
wx+ Like 'w+' but fails if path exists.
a Open file for appending. The file is created if it does not exist.
ax Like 'a' but fails if path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like 'a+' but fails if path exists.
EXAMPLE
CREATE A NEW, EMPTY FILE USING THE OPEN()
METHOD:

Program:
var fs = require('fs');
fs.open('newfile.txt', 'w', function (err, data)
{
if (err) throw err;
console.log('Empty File
Created!');
});
WRITING FILE
const fs = require('fs');
fs.writeFile(filename, data[, options], callback)
 filename: Full path and name of the file as a
string.
 Data: The content to be written in a file.

 options: The options parameter can be an object

or string which can include encoding, mode and


flag. The default encoding is utf8 and default flag
is "r".
 callback: A function with two parameters err and

fd. This will get called when write operation


completes.
CREATING & WRITING FILE
var fs = require('fs');
fs.writeFile('test.txt', 'Hello World!', function
(err) {
if (err)
console.log(err);
else
console.log('Write operation
complete.');
});
APPEND FILE CONTENT
var fs = require('fs');

fs.appendFile('test.txt', 'welcome to node js!',


function (err) {
if (err)
console.log(err);
else
console.log('Append operation
complete.');
});
RENAME FILES
const fs = require('fs');
fs.rename(existingfilename, newfilename,
callback)
var fs = require('fs');
fs.rename('test.txt', 'modify.txt', function (err) {
if (err)
console.log(err);
else
console.log('File Name Changed !');
});
DELETE FILE
const fs = require('fs');
fs.unlink(filename, callback)
var fs = require('fs');
fs.unlink('sample.txt', function (err) {
if (err)
console.log(err);
else
console.log('File Deleted !');
});
Copy file content:
var fs = require('fs');
fs.readFile('sample.txt', 'utf8',function (err, data)
{
if (err) throw err;
console.log(data);
fs.writeFile('test.txt', data, function (err) {
if (err)
console.log(err);
else
console.log('Write operation complete.');
});

});
console.log('Open a File to Reading');
Merge file data
var fs = require('fs');
var content="";
fs.readFile('sample.txt', 'utf8',function (err, data)
{
if (err) throw err;
content=content+data;
console.log('First File Data Copied.'+content);
fs.readFile('test.txt', 'utf8',function (err, data)
{
if (err) throw err;
content=content+data;
console.log('Second File Data Copied.'+content);
fs.writeFile('mergefile.txt', content, function (err)
{
if (err)
console.log(err);
else
console.log('Merge operation complete.'+content);
});
});
});

You might also like