Node JS Presenetation
Node JS Presenetation
Node JS Presenetation
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
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.
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()
var dept=“CSE”
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
g method.'));
NODE.JS - REPL TERMINAL
structure.
Print − Prints the result.
>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")
undefined
> do
{
... 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.
previous commands.
tab Keys − list of current commands.
.help − list of all commands.
to a file.
.load filename − load file content in current Node REPL
session.
node.js console.warn()
The console.warn() function is used to
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
res.writeHead(Status_code, Response_type);
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>”);
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?
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
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:
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
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
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.
});
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);
});
});
});