Unit 3
Unit 3
INTRODUCTION TO
NODE.JS
INTRODUCTION TO NODE.JS
INTRODUCTION TO NODE.JS
INTRODUCTION TO NODE.JS
INTRODUCTION TO NODE.JS
INTRODUCTION TO NODE.JS
INTRODUCTION TO NODE.JS
INTRODUCTION TO NODE.JS
▪ Node.js is an open-source and cross-platform JavaScript runtime
environment.
▪ Node.js uses JavaScript on the server.
▪ Node.js runs the V8 JavaScript engine, the core of Google Chrome,
outside of the browser. This allows Node.js to be very performant.
▪ A Node.js app runs in a single process, without creating a new thread
for every request.
V8 JAVASCRIPT ENGINE
▪ V8 is the name of the JavaScript engine that powers Google Chrome. It's the thing that
takes our JavaScript and executes it while browsing with Chrome.
▪ V8 provides the runtime environment in which JavaScript executes. The DOM, and the
other Web Platform APIs are provided by the browser.
▪ The JavaScript engine is independent of the browser in which it's hosted. This key feature
enabled the rise of Node.js.
Other browsers have their own JavaScript engine:
▪ Firefox has SpiderMonkey
▪ Edge was originally based on Chakra but has more recently been rebuilt using Chromium
and the V8 engine.
▪ Many others exist as well.
NODE.JS
NODE.JS
NODE.JS
NODE.JS
NODE.JS
NODE.JS
WORKFLOW
DIFFERENCES BETWEEN NODE.JS AND THE BROWSER
▪ Both the browser and Node.js use JavaScript as their programming language.
▪ Building apps that run in the browser is a completely different thing than building
a Node.js application.
▪ In the browser, most of the time what you are doing is interacting with the DOM, or
other Web Platform APIs like Cookies. Those do not exist in Node.js, of course. You
don't have the document, window and all the other objects that are provided by the
browser.
▪ And in the browser, we don't have all the nice APIs that Node.js provides through
its modules, like the filesystem access functionality.
ADVANTAGES OF NODE.JS
▪ Asynchronous and Event Driven: All 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: Node.js uses a single threaded model with
event looping.
▪ global packages are all put in a single place in your system (exactly
where depends on your setup), regardless of where you run
▪ npm install -g <package-name>
NPM DEPENDENCIES AND DEVDEPENDENCIES
▪ When you install an npm package using
npm install <package-name>, you are installing it as a dependency.
When you make a new release, You should follow the rules:
▪ you up the major version when you make incompatible API changes
▪ you up the minor version when you add functionality in a backward-compatible
manner
▪ you up the patch version when you make backward-compatible bug fixes
SEMANTIC VERSIONING USING NPM
▪ npm set some rules we can use in the package.json file to choose which versions
it can update our packages to, when we run npm update.
▪ ^: It will only do updates that do not change the leftmost non-zero number i.e
there can be changes in minor version or patch version but not in major version.
If you write ^13.1.0, when running npm update, it can update to 13.2.0, 13.3.0
even 13.3.1, 13.3.2 and so on, but not to 14.0.0 or above.
▪ ~: if you write ~0.13.0 when running npm update it can update to patch
releases: 0.13.1 is ok, but 0.14.0 is not.
▪ >: you accept any version higher than the one you specify
▪ >=: you accept any version equal to or higher than the one you specify
▪ <=: you accept any version equal or lower to the one you specify
SEMANTIC VERSIONING USING NPM
▪ <: you accept any version lower than the one you specify
▪ =: you accept that exact version
▪ -: you accept a range of versions. Example: 2.1.0 - 2.6.2
▪ ||: you combine sets. Example: < 2.1 || > 2.6
SEMANTIC VERSIONING USING NPM
▪ You can combine some of those notations, for example use 1.0.0 ||
>=1.1.0 <1.2.0 to either use 1.0.0 or one release from 1.1.0 up, but
lower than 1.2.0.
▪ no symbol: you accept only that specific version you specify (1.2.1)
▪ latest: you want to use the latest version available
PACKAGE.JSON FILE
▪ The package.json file is kind of a manifest for your project.
▪ here are no fixed requirements of what should be in a package.json file,
for an application.
▪ The only requirement is that it respects the JSON format, otherwise it
cannot be read by programs that try to access its properties
programmatically.
PACKAGE-LOCK.JSON FILE
▪ In version 5, npm introduced the package-lock.json file.
▪ The goal of package-lock.json file is to keep track of the exact version of
every package that is installed so that a product is 100% reproducible
in the same way even if packages are updated by their maintainers.
▪ The package-lock.json sets your currently installed version of each
package in stone, and npm will use those exact versions when running
npm ci.
▪ Same way like Composer in PHP.
▪ The dependencies versions will be updated in the package-lock.json file
when you run npm update.
REPL IN NODE.JS
▪ REPL (READ, EVAL, PRINT, LOOP) is a computer environment similar to
Shell (Unix/Linux) and command prompt.
▪ Node comes with the REPL environment when it is installed. System
interacts with the user through outputs of commands/expressions used.
▪ REPL is useful in writing and debugging the codes. The work of REPL can
be understood from its full form:
➢Read : It reads the inputs from users and parses it into JavaScript data
structure. It is then stored to memory.
➢Eval : The parsed JavaScript data structure is evaluated for the results.
➢Print : The result is printed after the evaluation.
➢Loop : Loops the input command. To come out of NODE REPL, press
ctrl+c twice
REPL IN NODE.JS
To start working with REPL environment of NODE; open up the terminal (in case of
UNIX/LINUX) or the Command prompt (in case of Windows) and write node and
press ‘enter’ to start the REPL.
Command:
➢10+12 //22
➢Math.ceil(10/3) //4
➢Math.round(2.56777) //3
➢Math.pow(3,4) //81
➢Math.sqrt(16) //4
➢for(var i=0;i<5;i++){console.log(i)} //0 1 2 3 4
VARIABLES
▪ Variables are defined in JavaScript using the var keyword.
▪ For Example,
var a=10;
console.log(a); //10
NODE.JS DATATYPE
console.log(a1[0]); //print 2
▪ Output:
[1]
[ 2, 1 ]
2
NODE.JS DATATYPE
// Variable store number data type
var a = 35;
console.log(typeof a); //number
// Variable store string data type
a = “Full Stack Development";
console.log(typeof a); //string
// Variable store Boolean data type
a = true;
console.log(typeof a); //boolean
// Variable store undefined (no value) data type
a = undefined;
console.log(typeof a); //undefined
OBJECT LITERALS
▪ Objects are written with curly braces {}. In Node.js, an object is a
mapping between the keys and values. The keys are strings and the
values can be anything.
▪ Objects can be extended arbitrarily at runtime.
▪ For Example:
var a={};
console.log(a); //{}
a.sub=1;
console.log(a); //{sub : 1}
OBJECT IN NODE.JS
▪ For Example:
var employee = {
name: "Soy",
age: "40",
department: "Software"
};
console.log(employee); //{ name: 'Soy', age: '40’,
department: 'Software' }
console.log(employee.name); //Soy
console.log(employee.age); //40
console.log(employee.department); //Software
OBJECT IN NODE.JS
▪ For Example:
var a= {
sub: “FSD”,
marks: [21, 65, 34],
unit: {
ReactJs: 2,
NodeJs: 4
}
};
console.log(a);
msg("John");
▪ Output:
Hello John
FUNCTION IN NODE.JS
▪ Anonymous function
▪ Arrow function
ANONYMOUS FUNCTION
▪ A function without a name is called an anonymous function.
▪ In JavaScript, you can assign a function to a variable. If you are going to use a
function as a variable, you don’t need to name the function.
▪ For Example:
var a1= function () {
console.log(“Function Call”);
}
a1(); //Function Call
ARROW FUNCTION
▪ Arrow function {()=>} is concise way of writing JavaScript functions in shorter
way.
▪ Arrow functions are anonymous functions i.e. functions without a name but they
are often assigned to any variable. They are also called Lambda Functions.
▪ For Example:
const a2 = () => {
console.log( “Full Stack development" );
}
var foo;
console.log(foo); // undefined
CLOSURE IN NODE.JS
▪ Whenever we have a function defined inside another function, the inner function has
access to the variables declared in the outer function.
function outerFunction(arg)
{
var v1 = arg;
function bar()
{
console.log(v1);
// Access a variable from the outer scope
}
// Call the local function to demonstrate that it has access to arg
bar();
}
outerFunction('hello closure!');
EXACT EQUALITY IN NODE.JS
▪ The Equality Operator (==)
The equality operator (==) checks whether two operands are the same and returns true if
they are the same and false if they are different.
The === operator means "is exactly equal to," matching by both value and data type. The
== operator means "is equal to," matching by value only.
x=7
x===7 is true
x==="7" is false
NULL
▪ Null is a special JavaScript object used to denote an empty object.
▪ It is different from undefined, which is used by JavaScript for nonexistent and
noninitialized values.
TRUTHY AND FALSY
▪ Truthy values are those that behave like true in Boolean operations and falsy values are those that behave
like false in Boolean operations.
▪ For example:
console.log(null == undefined); //true
console.log(null === undefined); //false
if(!false){
console.log(‘falsy1’); //falsy1
}
if(!null){
console.log(‘falsy2’); //falsy2
}
if(!undefined){
console.log(‘falsy3’); //falsy3
}
▪ Other important falsy values are 0 and the empty string (‘’). All object literals and arrays are truthy in
JavaScript.
this KEYWORD
▪ The JavaScript keyword this is passed to the function depending upon how you call it.
▪ It refers to the calling context.
▪ The calling context is the prefix used to call a function.
▪ For example:
var a={
fsd:123,
node:function(){
console.log('Inside function:',this.fsd); //Inside function: 123
}
}
console.log('a.fsd is:',a.fsd); //a.fsd is: 123
a.node();
this KEYWORD
var a={
a1:123
};
function f1()
{
console.log('Is this called from globals?:',this ===global);
console.log('Is this called from a?:',this===a);
}
Output:
f1(); Is this called from globals?: true
a.f1=f1; Is this called from a?: false
Is this called from globals?: false
a.f1(); Is this called from a?: true
this KEYWORD
function f1()
{
this.f1=456;
console.log('Is this called from global?:',this ===global);
}
f1();
console.log(global.f1);
f1.prototype.sub = "FSD";
const a1 = new f1('Node.js','React.js');
console.log("The subject is ",a1.sub);
Output:
Node.js , React.js
The subject is FSD
PROTOTYPE
function f1(){ }
f1.prototype.c='fsd';
Output:
var a1=new f1();
fsd
var b1=new f1(); fsd
console.log(a1.c); node.js
node.js
console.log(b1.c);
f1.prototype.c='node.js';
console.log(a1.c);
console.log(b1.c);
_ _proto_ _
▪ Every object which is created using literal syntax or constructor syntax
with the new keyword, includes __proto__ property that points to
prototype object of a function that created this object.
function Prototype
object1
object2
PROTOTYPE
function f1()
Output:
{ }; {}
undefined
var b=new f1(); {}
true
console.log(f1.prototype);
console.log(b.prototype);
console.log(b.__proto__);
console.log(b.__proto__===f1.prototype);
ERROR HANDLING
▪ Handling exceptions
An exception handler is a try/catch statement.
▪ Any exception raised in the lines of code included in the try block is handled in the
corresponding catch block:
try {
//lines of code
}
catch (e) {}
ERROR HANDLING
▪ Creating exceptions
An exception is created using the throw keyword:
throw value;
▪ Error objects
An error object is an object that is either an instance of the Error object, or
extends the Error class
throw new Error('Ran out of coffee')
ERROR HANDLING
try{
console.log('About to throw an error.');
throw new Error('Error thrown');
}
catch(e){
console.log('Error is thrown.');
console.log('Error caught:',e.message);
}
Output:
finally{ About to throw an error.
console.log('Finally block'); Error is thrown.
Error caught: Error thrown
} Finally block
NODEMON
▪ nodemon is a tool that helps to develop node.js based applications by
automatically restarting the node application when file changes in the
directory are detected.
require('dotenv').config();
process.env.USER_ID // "239482"
process.env.USER_KEY // "foobar"
process.env.NODE_ENV // "development"
node -r dotenv/config index.js command if you don't want to import the package in
your code.
HOW TO MAKE A NODE.JS CLI PROGRAM INTERACTIVE?
▪ readline module: get input from a readable stream such as the process.stdin
stream, which during the execution of a Node.js program is the terminal input,
one line at a time.
▪ Output:
0 : C:\Program Files\nodejs\node.exe
1 : d:\CGPIT\Subjects\FSD\Practicals\p1.js
2 : fsd
3:1
GLOBAL OBJECT IN NODE.JS
▪ Node.js Global Objects are the objects that are available in all modules.
▪ Global Objects are built-in objects that are part of the JavaScript and can be used
directly in the application without importing any particular module.
▪ __dirname
▪ __filename
▪ Timer
▪ Console
▪ Process
▪ exports
▪ module
▪ require()
__DIRNAME & __FILENAME IN NODE.JS
__dirname: The __dirname represents the name of the directory that the currently
executing script resides in.
__filename: The __filename represents the filename of the code being executed. This
is the resolved absolute path of this code file.
function printHello() {
console.log( "Hello, World!");
}
// Now call above function after 2 seconds
setTimeout(printHello, 2000);
TIMER IN NODE.JS
setInterval(cb, ms): The setInterval(cb, ms) global function is used to run callback
cb repeatedly after at least ms milliseconds
function printHello() {
console.log( "Hello, World!");
}
// Now call above function after 2 seconds
setInterval(printHello, 2000);
CONSOLE & PROCESS IN NODE.JS
▪ Console: Used to print information on stdout and stderr.
Example:
const moment=require('moment’);
var result = moment([2023, 8, 24]).from([2020, 1, 25]);
console.log(result);
console.log(moment().from('2025-11-17'));
Output:
in 4 years
2 years ago
MOMENT().ADD() FUNCTION
The moment().add() function is used add some days, months, and years into a
given date.
Syntax:
moment().add(Number, String |Duration | Object);
Example:
const days = moment().add(10, 'days').format('DD/MM/YYYY’);
const months = moment().add(2, 'months').format('DD/MM/YYYY’);
const years = moment().add(2, 'years').format('DD/MM/YYYY’);
console.log('Days', days); Output:
console.log('Months', months); Days 08/02/2024
Months 29/03/2024
console.log('Years', years);
Years 29/01/2026
(consider current date as 29/01/2024)
MOMENT().SUBTRACT() FUNCTION
The moment().subtract() function is used to subtract some days, months, and
years into a given date.
Syntax:
moment().subtract(Number, String |Duration | Object);
Example:
const days = moment().subtract(10, 'days').format('DD/MM/YYYY’);
const months =
moment().subtract(2,'months').format('DD/MM/YYYY’);
const years = moment().subtract(2, 'years').format('DD/MM/YYYY’);
console.log('Days', days);
console.log('Months', months); Output:
Days 19/01/2024
console.log('Years', years); Months 29/11/2023
Years 29/01/2022
(consider current date as 29/01/2024)
MOMENT().DIFF() FUNCTION
The moment().diff() function is used to compare two dates. It takes a date as its
first argument. A second input can be used to specify the time unit.
Syntax:
moment().diff(Date, String); Output:
Difference is 1236 days
Difference is 40 months
Example: Difference is 3 years
(consider current date as 29/01/2024)
const dateA = moment();
const dateB = moment('2020-09-10’);
console.log('Difference is ', dateA.diff(dateB, 'days'), 'days’);
console.log('Difference is ', dateA.diff(dateB, 'months'), 'months’);
console.log('Difference is ', dateA.diff(dateB, 'years'), 'years');
DATE COMPARISON METHOD
The moment.js library have isBefore(), isAfter(), and isSame() methods for
comparing dates. These methods return Boolean values that are indicating if one
date is before, after, or equal to another date.
Syntax:
moment().diff(Date, String);
Example:
console.log(moment().isAfter('2021-11-17'));
console.log(moment().isBefore('2021-12-15'));
console.log(moment().isSame());
Output:
true
false
true
EXAMPLE:
var n=new Date();
console.log('Now is:',n);
var ms=n.getMilliseconds();
var s=n.getSeconds(); Output:
Now is: 2024-01-29T06:39:56.898Z
var h=n.getHours(); 2024 0 29 12 9 56 898
var mn=n.getMinutes();
var d=n.getDate();
var m=n.getMonth();
var y=n.getFullYear();
console.log(y,m,d,h,mn,s,ms);
BUILT-IN MODULES IN NODE.JS
BUILT-IN MODULES IN NODE.JS
FILE SYSTEM MODULE
The fs module provides access to the filesystem.
▪ Output: ▪ Output:
The File System module has methods for creating new files:
fs.appendFile()
fs.open()
fs.writeFile()
FS MODULE: CREATE FILES
FS MODULE: UPDATE FILES
The File System module has methods for updating files:
fs.appendFile()
fs.writeFile()
FS MODULE: RENAME FILES
To rename a file with the File System module, use the fs.rename() method.
require('path').normalize('/users/joe/..//test.txt') //'/users/test.txt'
PATH MODULE
path.parse()
require('path').parse('/users/test.txt’)
output:
{
root: '/',
dir: '/users',
base: 'test.txt',
ext: '.txt',
name: 'test'
}
OS MODULE
▪ The os module provides a few basic operating-system related utility functions and
properties. The functions that you can use to retrieve information from the
underlying operating system and the computer the program runs on, and interact
with it.
const os = require('os’)
OS MODULE
Output:
Example: Platform: win32
Architecture: x64
var os = require('os'); Total Memory: 15.788383483886719
Available Memory: 7.952056884765625
console.log("Platform: " + os.platform());
Percentage consumed: 49.63349545644542
console.log("Architecture: " + os.arch()); This machine has 8 cpu
var gb=1/(Math.pow(1024,3));
console.log('Total Memory:',os.totalmem()*gb);
console.log('Available Memory:',os.freemem()*gb);
console.log('Percentage consumed:',100*(1-os.freemem()/os.totalmem()));
console.log('This machine has ',os.cpus().length);
NODE.JS OS MODULE
UTIL MODULE
▪ The util module contains a number of useful functions that are general purpose.
▪ The node.js "util" module provides some functions to print formatted strings as
well as some 'utility' functions that are helpful for debugging purposes.
▪ Use require('util') to access these functions.
UTIL MODULE
util.format(format, [...])
The util.format() is used to create formatted string from one or more
arguments. The first argument is a string that contains zero or more
placeholders. Each placeholder is then replaced using the remaining arguments
based on the meaning of the placeholder.
▪ List of placeholder :
% - Returns a single percent sign.
d - Treated as Number (both integer and float).
s - Treated as string and display as a string.
j - Represent JSON data.
UTIL MODULE
▪ Example:
var util=require('util');
var sub='node.js';
var marks=40;
console.log(util.format('%d marks in %s subject',marks,sub));
▪ Output:
40 marks in node.js subject
UTIL MODULE
util.log(string)
The function is used to write the string out to stdout, with timestamp.
▪ Example:
var util=require('util');
util.log('Message’);
▪ Output:
11 Dec 15:11:46 - Message
NODE.JS UTIL MODULE
▪ util.isArray(object): The function is used to check whether an 'object' is an array
or not. Returns true if the given 'object' is an Array, false otherwise.
▪ util.isDate(object): The function is used to check whether an 'object' is Date or
not. Returns true if the given 'object' is an Date, false otherwise.
▪ util.isError(object): The function is used to check whether an 'object' is Error or
not. Returns true if the given 'object' is an Error, false otherwise.
UTIL MODULE
▪ Example:
var util=require('util');
console.log(util.isArray([])); //true
console.log(util.isArray({a:10})); //false
console.log(util.isDate(new Date())); //true
console.log(util.isDate({})); //false
console.log(util.isError(new Error('This is an Error.'))); //true
console.log(util.isError({message: ‘FSD’})); //false