0% found this document useful (0 votes)
44 views

WT Unit-2 Node Js

Uploaded by

KAVAL VYAS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

WT Unit-2 Node Js

Uploaded by

KAVAL VYAS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Web Technology (WT)

(2101CS304)

Unit-02
NodeJS

Prof. Arjun V. Bala


Computer Engineering Department
Darshan Institute of Engineering & Technology, Rajkot
[email protected]
9624822202
 Outline
Looping

Introduction to NodeJS
NodeJS Modules
Node Package Manager
Creating Web Server
File System
Events
Traditional Programming Techniques
 Traditional programming does I/O the same way as it does local function calls: Processing
cannot continue until an operation finishes.
 This model of blocking when doing I/O operations derives from the early days of time
sharing systems in which each process corresponded to one human user.
 With the widespread use of computer networks and the Internet, this model of “one user, one
process” did not scale well.
 Multi-Threading programming is one alternative to this programming model, A thread is a
kind of lightweight process that shares memory with every other thread within the same
process, problem with multi-threading is programmer need to synchronize threads.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 3


Traditional Web Server Model
 In the traditional web server model, each request is handled by a dedicated thread from the
thread pool.
 If no thread is available in the thread pool at any point of time then the request waits till the
next available thread.
 Dedicated thread executes a particular request and does not return to thread pool until it
completes the execution and returns a response.
Thread
Pool

Thread 1 Executes Request 1

Requests Web Server Thread 2 Executes Request 2

Thread 3 Executes Request 3

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 4


Event Driven Programming
 Event-driven programming is a programming style whereby the flow of execution is
determined by events. Events are handled by event handlers or event callbacks.
 An event callback is a function that is invoked when something significant happens, such as
when the result of a database query is available or when the user clicks on a button.
 Consider how a query to a database is completed in typical blocking I/O programming:
1 result = query('SELECT * FROM posts WHERE id = 1');
2 do_something_with(result);

This query requires that the current thread or process wait until the database layer finishes processing it.
 In event-driven systems, this query would be performed in this way:
1 query_finished = function(result) {
2 do_something_with(result);
3 }
4 query('SELECT * FROM posts WHERE id = 1', query_finished);

In this technique query will send query to database and will process other task until database finishes
processing it and will call query_finished function when processing is done.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 5


Introduction to NodeJS
 Node.js is an open source, cross-platform runtime environment for developing server-side
and networking applications.
 Node.js is a platform built on Chrome's JavaScript runtime (V8 Engine) for easily building
fast and scalable network applications.
 Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient,
perfect for data-intensive real-time applications that run across distributed devices.
 Node.js applications are written in JavaScript, and can be run within the Node.js runtime on
OS X, Microsoft Windows, and Linux.
 Node.js also provides a rich library of various JavaScript modules which simplifies the
development of web applications using Node.js to a great extent.
 Node.js was developed by Ryan Dahl in 2009 and current version as of jan-2022 is 17.4.0 and
latest LTS (Long Term Support) version is 16.13.2.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 6


Features of NodeJS
 Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is,
non-blocking. It essentially means a Node.js based server never waits for an API to return
data. The server moves to the next API after calling it and a notification mechanism of Events
of Node.js helps the server to get a response from the previous API call.
 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 − Node.js uses a single threaded model with event
looping. Event mechanism helps the server to respond in a non-blocking way and makes the
server highly scalable as opposed to traditional servers which create limited threads to handle
requests. Node.js uses a single threaded program and the same program can provide service
to a much larger number of requests than traditional servers like Apache HTTP Server.
 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.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 7


Node.js Process Model
 Node.js processes user requests differently when compared to a traditional web server model.
 Node.js runs in a single process and the application code runs in a single thread and thereby
needs less resources than other platforms.
 All the user requests to your web application will be handled by a single thread and all the
I/O work or long running job is performed asynchronously for a particular request.
 So, this single thread doesn't have to wait for the request to complete and is free to handle the
next request. When asynchronous I/O work completes then it processes the request further
and sends the response.
Thread is free to serve
Node.js Server another request

Single Thread Event Loop Internal C++


Request 1 Thread Pool

Starts a async Job


Request 2 response
Async Job
response Works on
Async Job Completes Thread
Pool
Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 8
Installing Node
 For Windows and Mac operating system we can install node by downloading NPM from
https://nodejs.org/en/download/
 Just download the executable depending on your operating system and install it.
 For Linux we can use below commands to download node and NPM,
sudo apt install nodejs
sudo apt install npm
 We are going to explore more about NPM later in this chapter.
 To verify the installation we can open the terminal/command-prompt and fire the below
command.
node --version

 If above command returns some version information it means you have node installed in your system.
 If command returns error stating ‘node’ is not recognized as internal or external command it simply means
you don’t have node installed yet.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 9


Node REPL (Read Evaluation Print Loops)
 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.
 Node.js or Node comes bundled with a REPL
environment.
 It performs the following tasks −
 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.
 To start REPL environment we need to write only
“node” in terminal and it will start the REPL

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 10


Hello World using NodeJS
 To run basic HelloWorld Program in Node we need to create a JavaScript (js) file using any
text editor (we are going to use Visual Studio Code/Sublime).
HelloWorld.js
1 for(i=0;i<5;i++)
2 {
3 console.log('Hello World');
4 }

 Save the above file in a specific directory and navigate to that directory in the
terminal/command prompt.

 Now run the file with “node filename.js” command

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 11


Standard Callback Pattern / Continuation-passing style (CPS)
 Asynchronous programming does not use function return values to denote that a function is
finished, Instead it uses the continuation-passing style (CPS).
 Continuation-passing style (CPS) is a style of programming in which control is passed
explicitly in the form of a continuation.
 A function written in continuation-passing style takes as an extra argument an explicit
“continuation,” that is, a function of one argument. When the CPS function has computed its
result value, it “returns” it by calling the continuation function with this value as the
argument.
CallBack.js AnonymousFun.js
1 function printOutput(ans){ 1 function oddOrEven(n,funToCall){
2 console.log('Output is = '+ans); 2 if(n%2==0){
3 } 3 funToCall("even");
4 function oddOrEven(n,funToCall){ 4 }
5 if(n%2==0){ 5 else{
6 funToCall("even"); 6 funToCall("odd");
7 } else{ 7 }
8 funToCall("odd"); 8 }
9 } 9 oddOrEven(5,(ans)=>{
10 } 10 console.log('Output is = '+ans);
11 oddOrEven(5,printOutput); 11 });
Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 12
Modules
 JavaScript is one of the most frequently deployed programming languages in the world, the
core of the language was created quickly back in the Netscape days, in a rush to beat
Microsoft during the heat of the browser wars.
 The language was released prematurely, which inevitably meant it came out with some bad
features, despite its short development time, JavaScript also shipped with some really
powerful features.
 One major issue with the JavaScript was sharing the global namespace.
 Once you load JavaScript code into a web page, it is injected into the global namespace,
which is a common addressing space shared by all other scripts that have been loaded. This
can lead to security issues, conflicts, and general bugs that are hard to trace and solve.
 Thankfully, Node brings some order in this regard to server-side JavaScript and implements
the CommonJS modules standard.
 In this standard each module has its own context, separated from the other modules.
 This means that modules cannot pollute a global scope and cannot interfere with other modules.
 Dividing your code into a series of well-defined modules can help you keep your code under control.
Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 13
NodeJS Modules
 Node can have three types of modules
 Core Modules
 Modules which are shipped with the node and readily available to load.
 Some core modules which we are going to cover in this subject is
• http/https
• url
• path
• fs
• util
• os
• events
• Etc…
 Local Modules
 Modules which are created by the developer locally.
 In this subject we are going to learn how to create and load local modules.
 Third-party Modules
 Modules which are created by others (third-party) and available to download using node package manager.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 14


Loading Core Modules
 Node has several modules compiled into its binary distribution.
 These are called the core modules, are referred to solely by the module name (not the path)
and are loaded even if a third-party module exists with the same name.
 Syntax:
1 var module_reference = require('core_module_name');

 Example:
1 var http = require('http');

 Note: we are going to explore many core modules in details later in this unit.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 15


Using Local Module
 The CommonJS module system is the only circle.js
way you can share objects or functions 1 function r_squared(r) {
among files in Node. 2 return Math.pow(r, 2);
3 }
 For a sufficiently complex application you 4 function area(r) {
5 return Math.PI * r_squared(r);
should divide some of the classes, objects, or 6 }
functions into reusable well-defined 7 module.exports.area = area;
modules.
Here relative path is
 Here, circle.js has two functions and will mandatory for local
export the area method using the last line. app.js
module

 Now we can use circle module in other files 1 var cir = require('./circle');
2 console.log(cir.area(10))
by importing the module using require
method. We can omit .js in file path but
relative path (./) is mandatory.
1 node app.js
 To run the program we can simply use
command prompt and fire the node
app.js command in the same directory.
Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 16
Loading a Folder Module
 You can use the path for a folder to load a module similar to the file module like this
Syntax
1 var myModule = require('./myModulePath');

 Here,
 first node will try to find the myModulePath.js file in current directory, if file exists it will import that file
 If myModulePath.js does not exist in current directory it will try to find package.json file in
myModulePath folder, It will then parse the package.json file and find “main” attribute’s value as a relative
path for the entry point.
 If package.json not found in the folder it will consider index.js file as default “main” attribute value.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 17


Node Package Manager (NPM)
 You can download installable from the https://nodejs.org/en/download/
 Just follow basic installation process and it will install NPM (Node Package Manager) and
Node is included in the installation.
 NPM is
 A third-party package repository
 A way to manage packages installed
 A standard to define dependencies
 NPM provides a public registry service that contains all the packages that programmers
publish in NPM.
 NPM also provides a command-line tool to download, install & manage these packages.
 We can also use the standard package descriptor format (package.json) to specify which third
party modules your module/application depends on.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 18


NPM (Cont.)
 NPM has two main modes of operation:
 Global
 Local
These two modes change target directories for storing packages and have deep implications for how Node
loads modules.
 The Local Mode is the default mode of operation in NPM,
 In this mode, NPM works on the local directory level, never making system-wide changes.
 This mode is ideal for installing the modules as it will not affect other application which uses the modules
you are installing.
 The Global Mode is more suitable for installing modules that should always be available
globally, like that ones that provide command-line utilities and that are not directly used by
applications.
 Example: npm install –g express

-g flag represents global mode,


For local mode (default) we need not any flag.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 19


NPM (Cont.)
 Installing module
 We can use npm install command to install any package,
npm install package-name

 If you want to install a specific version of the package,


npm install package-name@version

 You can use basic operators like <,>,<= and >= while specifying version,
npm install package-name@"<0.3"
OR
npm install package-name@">=0.3 <0.5"

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 20


NPM (Cont.)
 Uninstalling a module
 If you want to uninstall locally installed package,
npm uninstall package-name

 If you want to remove globally installed package,


npm uninstall –g package-name

 Updating a module
 If you want to update locally installed package,
npm update package-name

 If you want to update globally installed package,


npm update –g package-name

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 21


Using package.json
 When coding a Node applications you can also include package.json file at the root.
 We can generate package.json file using npm init command.
 The package.json file is where you can define some of application metadata, such as the
name, author, repository, contacts and so on…
 The package.json is a JSON-formatted file that can contain a series of attributes, but for the
purpose of declaring the dependencies you only need one which is “dependencies”.
{  After creating package.json file you can
"name": "My App",
"version": "1.0.0", download and install the dependencies using
"dependencies": { command-line tool
"express": "0.1",
"request": "*", npm install
"nano": ">0.2.0"
…  To update the dependencies we can use

npm update

},

}
Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 22
Loading from the node_modules folder
 When we download/install packages using NPM, it will be stored in a folder named
node_modules.
 To load such packages we can use require method with absolute path.
 If provided path is absolute and not a core Node module, Node will try to find it inside the
node_modules folder. Here absolute path (no ./ in beginning) is
mandatory to load form node_modules folder
Syntax
1 var thirdPartyModule = require('thirdPartyModule');

 If Node fails to find the file, it will look inside the parent folder called
../node_modules/thirdPartyModule.
 If it fails again it will try the parent folder and keep descending until it reaches the root or
finds the required module.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 23


Core Node Modules
 There are many core node modules shipped with the node, here are some important modules
 path
 fs
 child_process
 os
 url
 querystring
 util
 events
 http

 We are going to explore each of this modules in next several slides.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 24


“path” Core Module
 The path module provides utilities for working with file and directory paths.
 It can be accessed using: Load
1 const path = require('path');
 Methods of path module
Method Description Example Output
normalize('path') It will normalizes the path.normalize('/foo/abc/..') /foo
given path,
resolving '..' and '.' segments.
join('path1','path2') It will joint two path and path.join('/foo', 'bar', 'abc') /foo/bar/abc
normalize it.
resolve('path1', 'path2') It will resolves a sequence of path.resolve('abc', 'xyz') /home/pathToABC/abc/xyz
paths into an absolute path
relative('path1', 'path2') It returns the relative path path.relative('/foo/bar', ../abc
from path1 to path2. '/foo/abc')
dirname('path') It will return the directory path.dirname(‘/foo/abc.txt') /foo
name.
basename('path') It will return the name of the path.basename(‘/foo/abc.txt‘) abc.txt (In Windows)
file.
Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 25
“fs” Core Module
 The fs module is where all the file query and manipulation functions are stored.
 With these functions, we can query files statistics, as well as open, read from, write to and
close files. Load
 It can be accessed using: 1 const fs = require('fs');

 Some important methods of “fs” module


 exists
 stat
 open
 readFile
 writeFile
 appendFile
 close

 We will see above methods with example in next few slides.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 26


“fs” Core Module (Cont.)
 The fs.exists() method is used to test whether the given path exists or not in the file system.
exists
1 const fs = require('fs'); It is not recommended to use exists as the
2 fs.exists('/path/to/file', (exists) => { parameters for exists callback are not consistent
3 console.log(exists ? 'Found' : 'Not Found!'); with other Node.js callbacks as most have err as
4 }); first parameter.

 The fs.stat() method is used to return information about the given file or directory. It returns
an fs.Stat object which has several properties and methods to get details about the file or
directory.
stat
1 const fs = require('fs');
2 fs.stat('index.js', (err,data) => {
3 console.log(data);
4 });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 27


“fs” Core Module (Cont.)
 What is Synchronous and Asynchronous approach?
 Synchronous approach: They are called blocking functions as it waits for each operation to complete,
only after that, it executes the next operation, hence blocking the next command from execution i.e. a
command will not be executed until & unless the query has finished executing to get all the result from
previous commands.
 Asynchronous approach: They are called non-blocking functions as it never waits for each operation to
complete, rather it executes all operations in the first go itself. The result of each operation will be handled
once the result is available i.e. each command will be executed soon after the execution of the previous
command. While the previous command runs in the background and loads the result once it is finished
processing the data.
Asynchronous (Non
Synchronous (Blocking)
Blocking)
1 const fs = require('fs'); 1 const fs = require('fs')
2 const data = fs.readFileSync('darshan.txt'); 2 fs.readFile('darshan.txt',(err,data)=>{
3 console.log(data.toString()); 3 console.log(data.toString())
4 });

 Note: it is better to use asynchronous approach for GUI based application as it will not block the
execution.
Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 28
“fs” Core Module (Cont.)
 To delete a file with the File System module, use the fs.unlink() method.
unlink
1 const fs = require('fs');
2 fs.unlink('darshan.txt', (err) => {
3 if(err){ throw err }
4 console.log("File Deleted");
5 });

 To rename a file with the File System module, use the fs.rename() method.
rename
1 const fs = require('fs');
2 fs.rename('darshan.txt', 'darshan_uni.txt', (err) => {
3 if(err){ throw err }
4 console.log("File Deleted");
5 });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 29


“child_process” Core Module

app.js
1 const child_process = require('child_process');
2 child_process.exec('dir',(err,stdout,stdin)=>{
3 console.log(stdout)
4 })

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 30


“os” Core Module
 OS is a node module used to provide information about the computer operating system.
 Task:
 Explore Methods from https://nodejs.org/api/os.html

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 31


“url” Core Module
 The URL module splits up a web address into readable parts.
 Parse an address with the url.parse() method, and it will return a URL object with each part of
the address as properties:
app.js
1 const url = require('url');
2 const adr = 'https://www.darshan.ac.in/abcd.js?FirstName=arjun&LastName=bala';
3 const q = url.parse(adr, true); // true here will also parse query string
4
5 console.log(q.host); //returns 'www.darshan.ac.in'
6 console.log(q.pathname); //returns '/abcd.js'
7 console.log(q.search); //returns '?FirstName=arjun&LastName=bala'
8
9 var qdata = q.query; //returns an object: { FirstName: arjun, LastName: 'bala' }
10 console.log(qdata.FirstName); //returns 'arjun'

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 32


Hello World (First App) in NodeJS
 Create a new file and save it as app.js
app.js
1 const http = require('http');
2
3 const server = http.createServer((req, res) => {
4 res.statusCode = 200;
5 res.setHeader('Content-Type', 'text/html');
6 res.end('Hello World');
7 });
8
9 server.listen(3000, () => {
10 console.log('Server running at http://127.0.0.1:3000/');
11 });

 To run the file we need to fire below command in terminal/command prompt


1 node app.js

 Above command will print ‘Server running at http://127.0.0.1:3000’, which means our first node server is
ready to serve, just use any browser and open the above URL to see Hello World

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 33


Event Emitter
 The event emitter provides a great way of making a programming interface more generic.
When we use a common understood pattern, clients bind to events instead of invoking
functions, making our program more flexible.
 Also, by using the event emitter, e get some features for free, like having multiple
independent listeners for the same events.
 In order to create an event emitter in Node, we need our class to inherit EventEmitter class
from the events module.
 Then we can use emit method of EventEmitter to emit the event.
app.js app.js (cont.)
1 EventEmitter = require('events') 1 var ticker = new MyEmitter();
2 class MyEmitter extends EventEmitter { 2
3 startTicks(){ 3 ticker.on("tick", function() {
4 setInterval(()=>{ 4 console.log("tick event fired");
5 this.emit('tick') 5 });
6 },1000); 6
7 } 7 ticker.startTicks();
8 }

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 02 – NodeJS 34

You might also like