[go: up one dir, main page]

0% found this document useful (0 votes)
81 views16 pages

NodeJs Notes - WebX

The document discusses Node.js dependencies and provides an example of a basic Node.js program. Node.js relies on several key dependencies including the V8 JavaScript engine, libuv for non-blocking I/O, http for HTTP parsing, c-ares for asynchronous DNS requests, OpenSSL for security, and zlib for compression. It also discusses npm as the package manager and tool for Node.js. An example program is shown to create an HTTP server and send a response.

Uploaded by

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

NodeJs Notes - WebX

The document discusses Node.js dependencies and provides an example of a basic Node.js program. Node.js relies on several key dependencies including the V8 JavaScript engine, libuv for non-blocking I/O, http for HTTP parsing, c-ares for asynchronous DNS requests, OpenSSL for security, and zlib for compression. It also discusses npm as the package manager and tool for Node.js. An example program is shown to create an HTTP server and send a response.

Uploaded by

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

5 Node.

js

Syllabus
enitter,
Environment setup, First app, Asynchronous programming, Callback concept, Event loops, REPL, Event
Networking moduie, Buffers, Streans, File system, Web module.

Jptroduction
Node.js is an open-source and cross-platform JavaScript runtime environment.
browser. This allows Node.js to
Node.js runs the V8 javaScript engine, the core of Google Chrome, outside of the
be very performant.
every request. Node.js provides a set of
A Node.js app runs in a single process, without creating a new thread for
and generally,
asynchronous I/0 primitives in its standard library that prevent JavaScript code from blocking
the exception rather
libraries in Node.js are written using non-bBocking paradigms, making blocking behaviour
than the norm.
a database or the file system,
When Node.js performs an I/0 operation, like reading from the network, accessing
operations when the
instead of biocking the thread and wasting CPUcycles waiting, Node.js will resume the
response comes back
single server without introducing the
This allows Node.js to handie thousands of concurrent connections with a
source of bugs.
burden of managing thread concurrency, which could be a significant
JavaScript for the browser are
Node.js has a unique advantage because millions of frontend developers that write
need to learn a completely
now able to write the server-s'de code in addition to the client-side code without the
different language.
as you do not have to wait for all vour
In Node.js the new ECMAScript standards can be used without problems,
by changing the
users to update their browsers - you are in charge of deciding which ECMAScript version to use
with flags.
Nodejs version, and you can also enable specific experimental features by running Node.js
engine, we
Node.js is built against modern versions of V8. By keeping up-to-date with the latest releases of this
in a timely
ensure new features from the JavaScript ECMA-262 specification are brought to Node.js developers
manner, as well as continued performance and stability improvements.
a specific binary
Node.js provides a simple way to list all dependencies and respective versions that ship with
following in your terninal to retrieve its
through the process global object. In case of the V8 engine, type the
version: node -p process.versions.v8
Internet Programming (MU) 5-2
Node.,js
5.1 Dependencies
There are several dependencies that Node.js relies on to
work the way it does.
5.1.1 Libraries

5.1.1(A) v8
The V8 library provides Node.js with a
JavaScript engine, which Node.js controls via the V8 C++ API. V8 is
maintained by Google, for use in Chrome.
5.1.1(B) iibuv
Another important dependency is libuv, a C library that is used to
consistent interface across all supported platforms. It provides abstract non-blocking I/0 operations to a
mechanisms to handle file system, DNS, network, child
processes, pipes, signal handling, poBling, and streaming.
5.1.1(C) lhttp
HTTP parsing is handled by a lightweight TypeScript and C
Iibrary called !lhttp.
5.1.1(D) c-ares
For some asynchronous DNS requests, Node.js uses a C
library called c-ares.
5.1.1(E) OpenSSL
OpenSSL is used extensively in both the tls and crypto modules. It
provides battle-tested implementations of
many cryptographic functions that the modern web relies on for security.

5.1.1(F) zlib
For fast compression and decompression, Node.js relies on the industry-standard zlib library, also known for its
use in gzip and libpng.

5.1.2 Tools

5.1/2(A) npm
Node.is is all about
Node pockaqe Manager
imodularity, and with that comes the need for aquality package manager; for this
npm was made. With npm comes the largest selection of purpose.
community-created packages of any programming
ecosystem, which makes building Node.js aPps quick and easy.The CLl runs fromn a terminal
and is how most
developers interact with npm.
The registry is a large public database of JavaScript software and the
meta-infornation surrounding it. npm with
its simple structure helped the ecosystem of Node.js proliferate, and now the
npm registry hosts over ,000,000
open-source packages you can freely use.

PDtatian
Internet Programming (MU) 5-3 Node.js

5.1.2(B) npx
Since npm version 5.2.0 npx is pre-bundled with npm. So,it is pretty much astandard nowadays. npx is also aCLI
tool whose purpose is to make it easy to install and manage dependencies hosted in the npmregistry. It is now
very easy to run any sort of Node.js based executable that you would normally install via npm
To check the version of npx installed you can use:

npx-version

Toexecute locally installed package use:


npxyour_package_name

5.2 My First Program

var lhttp = require("htp"):


http.createServer(function (request, response) {
response.writeHead(200, Content-Type': 'text/plain'});
respcnse end('Heito Wori\n);

)iisten(8081);
console.log('Server running at http://127.0.0.1:8081/);
write this code in notepad and save it with .js extension. Run the program with following command.

20de filename.js
you will get following output.
Server running at http://127.0.0.1:8081/
World".
Open browser and typehttp://127.0.0,1:8081/, It will show message "Hello
Explanation

var http = require("http");


We use the require directive to load Node.js modules, in this case it is 'http' module.
http.createServer(function()):
createServer function creates a server object. The function that's passed in to createServer is called once for
every HTTP request that's made against that server, so it's called the request handler. In fact, the Server cbject
returned by createServer is an EventEmitter, and what we have here is just shorthand for creating a server object
and then adding the listener later.

The function passes to createserver is The requestlistener is a function that is called each time the server gets a
request Therequest Listener function is passed as aparameter to the http.createServer) method. The
requestListener function handles requests from the user, and aBso the response back to the user

SE Tach knowledge
Pubiitatiant
Internet Programming (MU) 5-4 Node.js

When an HTTP request hits the server, node calls the request handler function with a few handy objects for
dealing with the transaction, request, and response.The req object represents the HTTP rozuest and has
properties for the request query string, parameters, body,HTTP headers, and so on. The res object represents the
HTTP response.
The response.writeHead() writes the HTTP header. The status code is a 3-digit HTTP status code, like 200 for
success. The last argument, headers, are the response headers. Optionally one can give a human-readable status
Message as the second argument.
The response.end ) writes the body and closes the response.
Finally there is http.createServer(function (request, response).listen) listen() method creates a listener on the
specified port or path.

5.3 Overview of Blocking vs Non-Blocking (Asynchronous Programming)


Blocking is when the execution of additional JavaScript in the Node.js process must wait until a non-javaScript
operation completes. This happens because the event loop is unable to continue running JavaScript while a
blocking operation Is occurring.
In Node.js, JavaScript that exhibits poor performance due to being CPUintensive rather than waiting on a non
JavaScript operation, suci as i/0, isn't typically referred to as blocking. Syrchronous methods in the Node.js
standard library that use libuv are the most commonly used blocking operations. Native modules nay also have
blocking methods.
Ailof the i/0 methods in the Node.js standard ibrary provide asynchroncus versions, which are non-blocking,
and accept calbeck functions. Some methods also have blocking counterparts, which have names that end with
Sync.

5.3.1 Blocking
const fs =require('fs'); fksyte.
const data =fs.read FileSync('mongo.js'): // blocks here until file is read
console.log(data);
console.log("hello");
here the file read function will block till the contents are read. This is evident from the fact that file data is prìnted
before "hello".

5.3.2 Non-biocking

const fs = require('fs');
fs.readFile('mongo.js', (err, data) => {
if ferr) throw err;
console.log(data);

R TechKnowledge
PuhtiCattons
5-5 Node,js
Internet Programming (MU)
console.log("hello"); // willrun before file contents
Here this is non-blocking function call. "hello" message will beprinted before file data.
choice that allows for
The ability to run more work) without waiting for the file read to complete, is a key design
higher throughput.

5.4 What are Callbacks


event response functions. These functions are
When there are events to happen in system, we need to write
other functions which are waiting for an event
called callbacks. These functions are passed on as parameters to some
to happen.

Function1(function2()0):
executed as a
happens link onclick) for a button. Function2 is
Here function1 may be called when an event
response to this event.

5,5 The Node.js Event Loop


non-blocking !/0 operaticns despite the fact that JavaScript is
The event loup is what allows Node.js to perferm
possible.
single-threaded by offloading operations to the system kerne! whenever
background.
can handle multiple operations executing in the
Since most modern kernels are multi-threaded, they
Node.js so that the appropriate callback may be added
When one of these operations completes, the kernel tells
executed.
to the poll queue to eventually be
event-driven
processes the provided input script. In an
When Node.is starts, it initializes the event loop, function when one
for events, and then triggers a callback
application, there is generally a main loop that listens
detected.
of those events is

Event Handlers
Event Emitters Events

Event Loop
Reduce -{}
Fig. 5.5.1
availabie
gets fired, its listener function starts executing Node.js has multiple in-built events
Whenever an event event-listeners as follows.
which are used to bind events and
through events module and EventEmitter class
var events =require('events');
own events.
where you can create-, fire-, and listen for- your
--Node.is has a buiit-in module, called "Events",

//Create an eventEmitter object


events.EvcntEmitrer);
var eventEmitter=new Tech Kngwledge
Puniiratidne
Internet Programming (MU) 5-6 Node.js

You carn assign event handlers to your own events with the EventEmitter object.
/Create an event handler as follows
var connectHandler = function connected() {
console.log('connection successful.);
7/ Fire the data_received event
eventEmitter.emit(çata received);
-emit is used to trigger an event

/ Bind the connection event with the handier

eventEmitter.on('connection', connectHandler);
--Adds a listener at the end of the listeners array for the specifiedevent.
1/Bind the data_received event with the anonymous function
eventEnitter.ondata received,function0{
console.log('data received successfully.);

/Fire the connection event

eventEmitter.emit['connection');
console.log("Program Ended."):
Output
connection successful.

data received successfully.


Program Ended.
HTTP requests

Single thread
Client
Callbacks

Long-running
operations

Non-blocking
workers

Fig. 5.5.2
TechKnousiedge
5-7 Node.js
Internet Programming (MU)
These are following steps:
Client sends HTTP requests to Node)S server.
1. Requests come to Event Loop (single thread), It passes overy request/response as Javascript to relevant worker
functions with callbacks.

2 Event loop wiilcontinue to wait for other requests.


3 As soon as it'sdone, resp0nse is sent back to main thread viacallback.
4 In the end Event Loop returns result to client.

5.5.1 Eyeht Loop Example

console.log("This is the first statement"); //statement 1


setTimecut(function0{
console.iog("This is the second statement"); //statement 2
}.1000):
Consolelog["This is the third satement"); //statement 3
cutput

This is the first statement

This is the third statement

This is the second statement

Explanation
The first statement is executed first. setTimeout) function wil! send seccnd statemert to sleep. Meanwhile third
statement is executed. Once the stack is empty, event loop will look for event in queue and execute the second

stateinent.

5.6 REPL

The repl module provides a Read-Eval-Print-Loop (REPL) implementation. It is a programming language


environment (basically a console window) that takes single expression as user input and returns the result back to
the console after execution.

1 Read: Reads user's input, parses the input inio JavaScript data-structure, andstores in memory.
2. Eval : Takes and evaluates the datastructure.

3 Print: Prints the result.

4. Loop: Loops the above command until the user presses ctrl-c twice.

Tech Knawledge
btitatlans

1mpet fs.
Internet Programming (MU) 5-8
Node.js

For working with REPI, just type node.


>a=2

>b=3
3

>c=a+b

This is like python.


For multiline statement:

var a=20

undefined

>do{

.consolelogía)
}while(a<iÐ);
21

Undefined

Here the return value is undefined. To remove it use command


repl.repl.ignoreUndefined=true

5.7 Node.js Net Module


Node.js provides the ability to perform socket programming. It contains methods for creating both servers and
clients.
The node net module provides an asynchronous wrapper for the network, and we include that with a require
callback.
statement. With that included, we can create a server object, which has a
The create server uses event listeners to control its operation, so we need to listen for those. The frst one that we
Want to listen for is the data listener. When we receive that we're going to have another call back that takes a
Darameter D. The other listener we want to listen for is the end listener.

Server: server,js
Var net=require ("net");
-networking module is added to project

var server = net.createServer();


-createserver will create a server

ecRKneuiledo
Teck
ub3tan
Internet Programming (MU) 5-9 Node.js
server.on('connection', handleConnection);
-handleconnection function is added to handle connection
server.listen(9000, function(0 {
console.log('server listening to %j', server.address0):
):
-server will listen toconhections on port 9000
function handleConnection(conn) {
var remoteAddress conn.remoteAddress ++ conn.remotePort;
console.log('new client connection from %s,remoteAddress);
conn.on(data', onConnData);
function willbe executed after receiving data
function onConnData(d) {
Consoie.log('connection data from %s: %j, remoteAddress, d);
conn write(d);

Run this code. Server will be created and program will block for incoming request. Keep it running.
Client: client.js
var net = requiref'net");
-net module is added

var client=new netSocket0;


var host="localhost";
-server address should be mentioned. If on same machine as of server then localhost
var port-9000;
-port number of server

client.connect( port, host, 0 =>{


conslelog("cient connected to ${host}:${port)");
client.write("Hello, Iam ${client.address0.address}");

-this function willconnect to server.


client.on(data', (data) =>{
console.log(Client received: ${data)');

this function is called when client receives data


Open another terminal and run client: node client.js

P Tech Kaawledge
PubHtatiaa
nternet Programming (MU) 5-10 Node.js
5.8 Buffers

Buffer objects are generally used for representing fixed length of sequence of bytes. Buffers are being supported
by Node.js APls.
The Buffer class is a class which is a subclass of Uint8Array' class of JavaScript. It has been extended with the
methods which cover more use cases.
The Buffer class makes available within the global scope. It lhas been recommended to explicitly use or reference
the Buffer class via import' or 'require'keyword statement.
The following code demonstrates the usage of "Buffer" class.
import (Buffer) from buffer';
-Initializes a zero-filled Buffer of lengh 20.
const buff1 = Buffer.alloc(20):
-Creates and initializes a Buffer of length20,
filled with bytes with the value 1
const buff2 = Buffer.alloc(20, 1):
const buff3 = Buffer.allccUnsafe(20);
-Creates and Initializes a Buffer containing the bytes |4, 5,6].
const buff4 =Buffer.from(14, 5,6|):

5.9 Streams

They are away to handle reading/writing files, network communications, or any kind of end-to-end information
exchange in an efficient way. Streams basically provide two major advantages over using other data handling
methods:
Memory efficiency: youdon't need to load large amounts of data in memory before you are able to process it
Time efficiency: it takes way less time to start processing data, since you can start processing as soon as you have
it, rather than waiting tillthe whole data payload is available
5.9.1 Readstream

var fs = require("fs");
-add fs module

var data =";


var readerStream=fs.createReadStream('index.html':
-create a readstream over file

readerStream.setEncoding('UTF8');

Techknowledge
Internet Programming (MU) 5-11 Node.js
-set encoding
readerStrean.on('data',function(chunk)
data + chunk;

-callback function on receiving data


readerStream.on('end',function0{
console.log(data);

-ending data
readerStream.on('error, function(err) {
console log(err.stack);

-in case of error

5.9.2 WriterStream

var fs = require"fs")
-add fs module;

var data ='Internet Programming';


var writerStream = fs.createWriteStream(output.txt);
-Create write strean

writerStream.write(data,'UTF8');
-writing data
writerStream.end):
-end of file

writerStream.on(finish', function0 {
console.log("Write completed.");

writerStream.on('error, function(err) {
console.log[err.stack);

console.log("Program Ended");

Pubtitatta a
Internet Programming (MU) 5-12 Node.js
5.10 File System
The Node.js file system module allows you to work with the file
system on your computer. With Node.]s, you can
programmatically manipulate files with the built-in fs module. The name is short for "6le svstem," and the module
contains ail the functions you need to read, write, and delete files on the local machine.
Common use for the File
System module:
Read files fs.readFile)
Create files fs.open0
Update files fs.writeFile), fs.appendFile)
Delete files fs.unlink)
Rename files :fs.rename0
fs.readFile (fileName ,options], callback)
flename : 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 defauit flag is "r".
Callback : Afunction with two parameters err and data. This will get called when readFile operation
completes.
This function reads file asynchronously andexecutes callback function when read operation completes. This read
operaticn either throws an error or completes successfuly. The err parameter contains error information if any. The
data parameter contains the content of the specified file.
Readinga file
var http = require('http');
-http module is added
var fs=require(fs');
-file system nodule is added
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
-file datais read
res.writeHead(200, (Content-Type':'text/html');
res.write(data);
-file data is written as a part of response body
return res.end)

}).listen(8080);
-listening to port 8080

lust open in the browser with url: http://localhost:8080/ and file content will be displayed on screen.

RE TechKnowledge
Pubiitattas
Internet Programming(MU) 5-13 Node.js
5.11 Neb Module

Node.js provides an http module which can be used to create an HTTP client of a server. Aweb module contains
web components and static web content files, such as images, which are called web resources.web servers support
server-side scripts, use scripting languages or redirecting the function to an application server that retrieves data
from a database and performs complex logic and then sends a response viathe Web server to the HTTP client. It
consists of:

Server : This layer has the Web server that can intercept the clients requests and transfer the
response to them.

Client : This layer consists of web browsers, mobile browsers, or applications capable of sending HTTP
requests to the server.

5.11.1 HTTP Connections

Here is a server

Server: httpserver.js
Nodejs includes ahttp module that can be used to build aserver's HTTP application. Following is the HTTP
servers bare ninimum structure

var http = require( http);


-http module is added
var fs = require('fs');
-fiel system model is added
var url = require('url');
-url model is added
http.createServer( function (request, response) {
fs.read Fi!e("index.html", function (err, data) {
if (err) {
console.log(err):
response.writeHead (404, ('Content-Type':'text/html');
}else (
response.writeHead(200, {'Content-Type': 'text/htm!):
response.write(data.toString):

response.end):;

}).listen(8081);
-http server is created which will listen on port 8081
console.log('Server running at http://127.0.0.1:8081/);
this server will return index.htmlto the client. So we need to create a file index.html in same directory.
<html>

Tech knawledge
Pubit attan
Internet Programming (MU) 5-14 Node.js

<head>
<title> Sample Page</title>
s/heads
<body>
Hello World!
</body>
</html>
Run thÉs server node httpserver.js
Output : Server running at http://127.0.0.1:8081/
Type the URL in browser and we can see "helloworld" or we can write aclient script.
Client: httpclient.js
You can builda Web client using the http module
var http = require('http);
-http module is added
var options=
host: localhost',
port: 3081",

-sever URL and port number is initialized


var calback = function(response) {
var body =";
response.on('data', function(data) {
body += data;
}):
response.on('end', function(){
console.log(body);

-callback function is added


var req = http.request(options, callback);
reg.end0:
output: node webclient,js
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>
R Tech Knawledge
Pubi4atE ans
Internet Progran1ming (MU) 5-15 Node.js

5.12 Node MongoDB Connection


We can connect nodoj to Mongodb server. MongoDB is a document database designed for ease of development
and scaling.
5.12.1 MongoDB
MongoDB is a document-oriented database program. Classified as a NoSQL database program, MongoDB uses
jSON-like documents with optional schemas. MongoDB is developed by MongoDB Inc. and licensed under the Server
Side Public License (SSPL).
A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB
documents are like JSON objects. The values of fields may include other documents, arrays, and arrays of docume:ts.

name:"Mumbai",
state: "Maharashtra"
status: "Metio"

rivers: "Mithi", "Dahisar"1

5.12.2 Installation

You can download MongoDBfrom https://www.mongodb.com/try/-download/community. Install the server.


ÁnosDB Cumpazs- bcac t217
Coorest He
Detabeses

Deabese Name Stocase Sice Cotections

322MS

config 120KB

Soca 60 CKB

32KB

82 OKB

32. 0KB

Acthvate Wintos

oType hére tó search

Fig 5.1:Mongodb
Internet Programming (MU) 5-16 Node.js
5.13 Connection

Create a database and a collection and then use following code to add records.
var MongoClient = require('mongodb'). MongoClient;
-MongoDB module is added
var url ="mongodb://localhost:27017/";
-URL of the mongodb server. Its localhost if server is on same machine
MongoClient.connect(url, function(err, db) {
-Connect to the server
if (err) throw err;
var dbo = db.db("vcet");
-connect to the database named "vcet"
var myobj =(name: "VCET", address: "KT marg Vasai" ;
dbo.ooilection("inft").insertOne(myobj, function(err, res) {
-connect to the collectio named "inft"
if (err) throw err;
console.log("1 document inserted");
db.close0:

This code will insert record into database. Node.js is better suited for backend. It has mcdules like filesystem. net,
http, database connections. One can use node.js with any frontend technology as well as database.

Review Questions

Q.1 What is Node JS? What are the features of Node JS?

Q. 2 What are different dependencies of Node JS


Q.3 Write a program to display "Hello World" using Node JS? Write step wise process.
Q. 4 What do you mean by Asynchronous programming?
Q. 5 What are callbacks?

Q. 6 Describe Event Loop with example.


a.7 Describe REPL Module.

Q. 8 Describe Node.js Net Module.


Q.9 What are Buffers and Streams?
Q. 10 Explain File System of Node JS in detail.
Q. 11 Explain Web Module of Node JS.
Q. 12 What is MongoDB? Describe the connection between MongoDB and Node JS.

You might also like