NodeJs Notes - WebX
NodeJs Notes - WebX
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
)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
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.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.
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.
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",
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
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.);
eventEmitter.emit['connection');
console.log("Program Ended."):
Output
connection successful.
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.
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
1 Read: Reads user's input, parses the input inio JavaScript data-structure, andstores in memory.
2. Eval : Takes and evaluates the datastructure.
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
>b=3
3
>c=a+b
var a=20
undefined
>do{
.consolelogía)
}while(a<iÐ);
21
Undefined
Server: server,js
Var net=require ("net");
-networking module is added to project
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
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
readerStream.setEncoding('UTF8');
Techknowledge
Internet Programming (MU) 5-11 Node.js
-set encoding
readerStrean.on('data',function(chunk)
data + chunk;
-ending data
readerStream.on('error, function(err) {
console log(err.stack);
5.9.2 WriterStream
var fs = require"fs")
-add fs module;
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.
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
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",
name:"Mumbai",
state: "Maharashtra"
status: "Metio"
5.12.2 Installation
322MS
config 120KB
Soca 60 CKB
32KB
82 OKB
32. 0KB
Acthvate Wintos
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?