0% found this document useful (0 votes)
18 views111 pages

Unit 3

This document provides an introduction to Node.js, including: 1) Node.js is a JavaScript runtime environment that uses the V8 engine and allows JavaScript to be used on the server-side. 2) It differs from browser JavaScript in that it does not provide browser/DOM APIs and is used to build server applications instead of client-side code. 3) Node.js applications are asynchronous and event-driven, use non-blocking I/O, and are very fast due to being built on the V8 engine.

Uploaded by

Ben Men
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)
18 views111 pages

Unit 3

This document provides an introduction to Node.js, including: 1) Node.js is a JavaScript runtime environment that uses the V8 engine and allows JavaScript to be used on the server-side. 2) It differs from browser JavaScript in that it does not provide browser/DOM APIs and is used to build server applications instead of client-side code. 3) Node.js applications are asynchronous and event-driven, use non-blocking I/O, and are very fast due to being built on the V8 engine.

Uploaded by

Ben Men
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/ 111

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

▪ Safari has JavaScriptCore (also called Nitro)

▪ 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.

▪ No Buffering: Node.js applications never buffer any data. These applications


simply output the data in chunks.
NPM PACKAGE MANAGER
▪ npm is the standard package manager for Node.js.
▪ npm manages downloads of dependencies of your project.
NPM GLOBAL OR LOCAL PACKAGES
▪ local packages are installed in the directory where you run npm
install <package-name>, and they are put in the node_modules
folder under this directory

▪ 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.

▪ The package is automatically listed in the package.json file, under the


dependencies list (as of npm 5: before you had to manually specify --
save).
▪ When you add the -D flag, or --save-dev, you are installing it as a
development dependency, which adds it to the devDependencies list.
NPM GLOBAL OR LOCAL PACKAGES
NPM GLOBAL OR LOCAL PACKAGES
▪ If a project has a package.json file, by running
npm install
SEMANTIC VERSIONING USING NPM
The Semantic Versioning concept is simple: all versions have 3 digits: x.y.z.
▪ the first digit is the major version
▪ the second digit is the minor version
▪ the third digit is the patch version

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.

▪ There are other rules, too:

▪ 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

▪ Node.js is highly performant and it uses JavaScript because


JavaScript supports first-class functions and closures.

▪ Node.js has a few core types: number , boolean , string , and


object.
NUMBERS
▪ All numbers in JavaScript have the same floating point number type.
▪ Arithmetic operations (+, -, *, /, %) work on numbers.
▪ For Example:
var a=12;
var b=5;
console.log(a+ 10); //22
console.log(a/b); //2.4
console.log(a * b); //60
console.log(a – b); //7
console.log(a % 7); //reminder: 5
BOOLEAN
▪ Two literals are defined for Boolean values: true and false.
▪ You can assign these to variables and apply Boolean operations to them.
▪ For Example:
var a= true;
console.log(a); //true

//Boolean operations (&&, ||, !) work as expected:


console.log(true && true); //true
console.log(true && false); //false
console.log(true || false); //true
console.log(false || false); //false
console.log(!true) //false
console.log(!false); //true
ARRAYS
▪ You can create arrays easily in JavaScript using [].
▪ For Example:
var arr1 = new Array();
var arr2 = [];
var arr1 = ['apple', 'banana', 'pear', 'orange’];
for (var i = 0; i < arr1.length; i++)
{
console.log(arr1[i]);
}
▪ Output:
apple
banana
pear
orange
ARRAYS
▪ For Example:
var a1 =[];
a1.push(1); //add at the end
console.log(a1); //print 1
a1.unshift(2); //add at the top
console.log(a1); //print [2, 1]

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);

Output: { sub: 'FSD', marks: [ 21, 65, 34 ], unit: { ReactJs: 2, NodeJs: 4 } }


FUNCTION IN NODE.JS
▪ A Node.js function is defined with the function keyword, followed by a name. Function
parameters are listed inside the parentheses () in the function definition.
▪ Syntax:
function functionName(){
//function body
//optional return;
}
▪ Example:
function msg(name)
{
console.log("Hello "+name);
}

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" );
}

a2(); //Full Stack development


DEFAULT VALUE IN NODE.JS
▪ The default value of any variable in JavaScript is undefined.

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 Identity Operator (===)


The identity operator checks whether two operands are “identical”.

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);

var a=new f1();


console.log(a.f1);
▪ Output:
Is this called from global?: true
456
Is this called from global?: false
456
PROTOTYPE
▪ Every object in JavaScript has an internal link to another object called
the prototype.
▪ The prototype is an object that is associated with every functions and
objects by default in JavaScript, where function's prototype property is
accessible and modifiable and object's prototype property is not
visible.
▪ Every function includes prototype object by default.

▪ All JavaScript objects inherit properties and methods from a prototype.

▪ The Object.prototype is on the top of the prototype inheritance chain.


USING THE PROTOTYPE PROPERTY
The JavaScript prototype property allows you to add new properties to object
constructors:

function f1(sub1 , sub2) {


console.log(sub1,", ",sub2);
}

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.

▪ npm install -D nodemon


▪ nodemon pr1.js
ENVIRONMENT VARIABLES FROM NODE.JS
▪ The variable which exists outside code is a part of server
environment and can help by both streamlining and making more
secure the process of running script and applications.
▪ During the application initialization, these are loaded into
the process.env and accessed by suffixing the name of the variable.
▪ Environment variables in backend applications relies on the commands
of the operating system to define the environment variables along with
their value. A system administrator may define it through a shell-script
instead of a CLI interface. Environment variables typically aren’t
globally accessible across the operating system, they are usually
session-specific.
READ ENVIRONMENT VARIABLES FROM NODE.JS
▪ The process core module of Node.js provides the env property which
hosts all the environment variables that were set at the moment the
process was started.
▪ npm install dotenv
▪ create an .env file in the root directory of your project, and then use the
dotenv package to load them during runtime.
# .env file
USER_ID="239482"
USER_KEY="foobar"
NODE_ENV="development"
READ ENVIRONMENT VARIABLES FROM NODE.JS

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.

const readline = require('readline').createInterface({


input: process.stdin,
output: process.stdout
})
Output:
readline.question(`What's your name?`, name => { What’s your name? John
console.log('Hi,',name); Hi, John
readline.close()
})
COMMAND LINE ARGUMENTS
▪ argv property, which is an array that contains all the command line
invocation arguments.
▪ The first element is the full path of the node command.
▪ The second element is the full path of the file being executed.
▪ Remaining elements are the command line arguments.
▪ Example:
console.log(process.argv[0]); //C:\Program Files\nodejs\node.exe
console.log(process.argv[1]); //d:\CGPIT\Subjects\FSD\p1.js
COMMAND LINE ARGUMENTS
▪ Example:
process.argv.forEach((val, index) => {
console.log(index,':', val);
})

▪ Command: node p1.js fsd 1

▪ 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.

console.log( __dirname ); //d:\CGPIT\Subjects\FSD

__filename: The __filename represents the filename of the code being executed. This
is the resolved absolute path of this code file.

console.log( __filename ); //d:\CGPIT\Subjects\FSD\p1.js


TIMER IN NODE.JS
setTimeout(cb, ms): The setTimeout(cb, ms) global function is used to run callback
cb after at least ms milliseconds.

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.

▪ Process: Used to get information on current process. Provides multiple events


related to process activities.
Node.js require() FUNCTION
▪ The Node.js require function is the main way of importing a module into the
current file.
▪ There are three kinds of modules in Node.js: core modules, file modules and
external node_modules, all of which use the require function.
▪ When we make a require call with a relative path- for example, like
require(‘./filename’) or require(‘../foldername/filename’)- Node.js runs the
destination JavaScript file in a new scope and return whatever was the final value
for module.exports in that file.
Node.js module.exports
▪ The items that we intend to export from a module should be attached to the
module.exports variable.
▪ It is important to note that module.exports is already defined to be a new empty
object in every file.
▪ That is, module.exports={} is implicitly present.
▪ Example:
console.log(module.exports); //{}
CREATE OWN MODULE
▪ Node.js follows the CommonJS module specification.
▪ Following are few points of the module system:
o Each file is its own module.
o Each file has access to the current module definition using the module variable.
o The export of the current module is determined by the module.exports
variable.
o To import a module, use the globally available require function.
EXAMPLE: CREATE OWN MODULE (single object)
▪ Create Module: ▪ Fetch module in file:

var a=function(){ var a1=require('./t1');


console.log('Fetching the data a1();
from t1 module');
};
module.exports=a;
EXAMPLE: CREATE OWN MODULE (more than 1 object)
▪ Create Module: ▪ Fetch module in file:
var a=function(){
console.log('Fetching the data from t1 var a1=require('./t1');
module:a');
a1.a();
};
a1.b();
var b=function(){
console.log('Fetching the data from t1
module:b');
};
module.exports={
a:a,b:b
};
Handling Date/Time using Moment
The moment module is used for parsing, validating, manipulating, and
displaying dates and times in JavaScript.
▪ Feature of moment module:
- It is easy to get started and easy to use.
- It is widely used and popular for formatting date and time.

• Installation of moment module:


Install this package by using this command: npm install moment
Check moment version using the command: npm ls moment
MOMENT().FORMAT() FUNCTION
The moment().format() function is used to format the date according to the user
need. The format can be provided in string form which is passed as a parameter to
this function.
Syntax: Output:
moment().format(String); 2024-01-29T11:37:27+05:30
January 29th 2024, 11:37:27 am
Example: Monday
var moment = require('moment’); Jan 29th 24
console.log(moment().format());
console.log(moment().format('MMMM Do YYYY, h:mm:ss a'));
console.log(moment().format('dddd'));
console.log(moment().format("MMM Do YY"));
MOMENT().FROM() FUNCTION
The moment().from() function is used to calculate the time from any other time in
Node.js. It takes a date as a parameter and calculates the time from that date.
Syntax:
moment().from(Moment|String|Number|Date|Array, Boolean);

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.

To include the File System module, use the require() method:


var fs = require('fs’);

Common use for the File System module:


▪ Read files
▪ Create files
▪ Update files
▪ Delete files
▪ Rename files
fs Module- read and write
var fs=require('fs’);
//write
fs.writeFileSync('t1.txt','Testing!!!’);
//read
console.log(fs.readFileSync('t1.txt').toString());
fs Module- delete file
▪ Synchronous version: ▪ Asynchronous version:

var fs=require('fs'); var fs=require('fs');


try{ fs.unlink('t1.txt',function(err){
fs.unlinkSync('t2.txt'); if(err){
console.log('File deleted'); console.log('Error:',err);
} }
catch(err){ else{
console.log('Error:',err); console.log('File deleted');
} }})
console.log(‘Program End'); console.log(‘Program End’);

▪ Output: ▪ Output:

File deleted Program End


Program End File deleted
FILE MODE
▪ r+ open the file for reading and writing, if file doesn't exist it won't be created.
▪ w+ open the file for reading and writing, positioning the stream at the beginning of
the file. The file is created if not existing.
▪ a open the file for writing, positioning the stream at the end of the file. The file is
created if not existing.
▪ a+ open the file for reading and writing, positioning the stream at the end of the
file. The file is created if not existing.
FS MODULE: CREATE/ UPDATE FILES

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.

The fs.rename() method renames the specified file:


NODE.JS CALLBACK CONCEPT
▪ A callback is a function which is called when a task is completed, thus helps in
preventing any kind of blocking and a callback function allows other code to run in
the meantime.
▪ Callback is called when task get completed and is asynchronous equivalent for a
function.
▪ Using Callback concept, Node.js can process a large number of requests without
waiting for any function to return the result which makes Node.js highly scalable.
NODE.JS CALLBACK CONCEPT
Code for reading a file Code for reading a file asynchronously
synchronously (blocking code) in (non-blocking code) in Node.js.
Node.js.

var fs = require("fs"); var fs = require("fs");


var filedata = fs.readFile('inputfile1.txt', function (ferr,
fs.readFileSync('inputfile1.txt'); filedata) {
console.log(filedata.toString()); if (ferr) return console.error(ferr);
console.log("End of Program execution"); console.log(filedata.toString());
});
console.log("End of Program execution");
PATH MODULE
▪ Use reuire(‘path’) to load this module.
▪ The path module exports functions that provide useful string transformation
common when working with the file system.
▪ The key motivation for using the path module is to remove inconsistencies in
handling file system paths.
▪ Given a path, you can extract information out of it using those methods:
o dirname: get the parent folder of a file
o basename: get the filename part
o extname: get the file extension
PATH MODULE
const path = require('path')
const notes = ‘/subjects/fsd/notes.txt’
console.log(path.dirname(notes) ) // /subjects/fsd
console.log(path.basename(notes) ) // notes.txt
console.log(path.extname(notes) ) // .txt
console.log(path.basename(notes, path.extname(notes))) //notes
PATH MODULE
path.join(): Joins two or more parts of a path.
const name = 'joe'
path.join('/', 'users', name, 'notes.txt’) //'/users/joe/notes.txt’

path.normalize(): Tries to calculate the actual path when it contains relative


specifiers like . or .., or double slashes:

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

You might also like