SlideShare a Scribd company logo
Web Frameworks
Node JS functions & Modules
1
Monica Deshmane(H.V.Desai College,Pune)
Topics
• Functions
• Module and Module Types
• Core Module, Local Module
• Directories as module
• Module.exports
Monica Deshmane(H.V.Desai College,Pune) 2
Functions
»JavaScript is a functional
programming language
»A normal function structure in
JavaScript is defined as follows.
• function functionName()
{ // function body
// optional return;
}
3
Monica Deshmane(H.V.Desai College,Pune)
Functions
–All functions return a value in
JavaScript.
–If no explicit return statement, a
function returns undefined.
function myData() { return 123; }
console.log(myData()); // 123
function myValue() { }
console.log(myValue()); // undefined
4
Monica Deshmane(H.V.Desai College,Pune)
Functions continue...
• create a function:
function hello(name)
{ console.log("hello " + name);
}
hello(“John");
• To declare parameters for a function in JavaScript, list them in
the parentheses.
• There is no checking of these parameters at runtime:
function hello(name) { console.log("hello " + name); }
hello();
//hello
undefined 5
Monica Deshmane(H.V.Desai College,Pune)
Functions continue...
hello("CSS", "HTML", "AAA", 4);
//hello CSS
• If less parameters passed to function
others are of type undefined.
• If too many are passed extras are
simply unused.
• All functions have a predefined array in
the body called arguments.
6
Monica Deshmane(H.V.Desai College,Pune)
Functions continue...
Functions in JavaScript with no
names called anonymous functions.
• var x = function (a, b)
{ return a + b; }
• console.log(x(10, 20));
7
Monica Deshmane(H.V.Desai College,Pune)
Functions continue...
Function Scope
• Every time a function is called, a new
variable scope is created.
• Variables declared in the parent scope are
available to that function.
var pet = 'cat';
function myMethod() { var pet = 'dog';
console.log(pet); //dog
}
myMethod();
console.log(pet); //cat
8
Monica Deshmane(H.V.Desai College,Pune)
Module and Module Types
Node.js Module
• Module in Node.js is
functions in single or multiple
JavaScript files for reusability.
• Each module in Node.js has its own context, so
it cannot
interfere with other modules
• Also, each module can be placed in a separate
.js file under a
separate folder.
Monica Deshmane(H.V.Desai College,Pune) 9
Module and Module Types
Node.js Module Types
Node.js includes three types of modules:
1. Core Modules
2. Local Modules
3. Third Party Modules
Monica Deshmane(H.V.Desai College,Pune) 10
1)Local/own Modules
• Create Your Own Modules
Create a module that returns the
current date and time:
exports.myDateTime = function ()
{
return Date();
};
• Use the exports keyword to make properties and
methods available outside the module file.
Save the code above in a file called
"myfirstmodule.js"
Monica Deshmane(H.V.Desai College,Pune) 11
Own Modules
• Include Your Own Module
Use the module "myfirstmodule" in a
Node.js file:
var http = require('http');
var dt = require('./myfirstmodule');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " +
dt.myDateTime());
res.end();
}).listen(8080);
Monica Deshmane(H.V.Desai College,Pune) 12
2)Node.js Core/ built in Modules
 Core Module & its Description
• http - http module includes classes,
methods and events to create
Node.js http server.
• url - url module includes methods for
URL resolution and parsing.
• Querystring-querystring module includes methods to deal
with query string.
• Path - path module includes methods to deal with file
paths.
• Fs - fs module includes classes, methods, and
events to work with file I/O.
• Util - util module includes utility functions useful for
programmers.
Monica Deshmane(H.V.Desai College,Pune) 13
Loading Core Modules
• In order to use Node.js core or NPM
modules, you first need to import it using
require() function as shown below.
var module = require('module_name');
Monica Deshmane(H.V.Desai College,Pune) 14
Loading Core Modules
Example: Load and Use Core http
Module
var http = require('http');
var server =
http.createServer(function(req, res)
{ //write code here } );
server.listen(5000);
Monica Deshmane(H.V.Desai College,Pune) 15
Directories as module
• Folders as Modules#
• There are ways in which a folder may be
passed to require() as an argument.
• The first is to create a package.json file in the
root of the folder, which specifies
a main module.
• An example package.json file might look like
this:
{ "name" : "some-library",
"main" : "./lib/some-library.js" }
Monica Deshmane(H.V.Desai College,Pune) 16
Module.exports OR
Export Module in Node.js
• Here, you will learn how to expose
different types as a module using
module.exports.
• The module.exports is a special object which is
included in every JavaScript file in the Node.js
application by default.
• The module is a variable that represents the
current module, and exports is an object that
will be exposed as a module.
• So, whatever you assign to module.exports will
be exposed as a module.
• Let's see how to expose different types as a
module using module.exports.
Monica Deshmane(H.V.Desai College,Pune) 17
Module.exports / Export Module
in Node.js
• Export Literals
• As mentioned above, exports is an object.
So it exposes whatever you assigned to it as
a module.
• For example, if you assign a string literal
then it will expose that string literal as a
module.
• The following example exposes simple
string message as a module in Message.js.
• Message.js
module.exports = “Hello world”;
• Now, import this message module and use
it as shown below.
Monica Deshmane(H.V.Desai College,Pune) 18
Module.exports / Export Module
in Node.js
• app.js
var msg = require('./Messages.js');
console.log(msg);
• Run the above example and see the result,
as shown below.
• C:> node app.js
Hello World node app.js
Hello World
• Note:You must specify ./ as a path of root folder to import a
local module.
• However, you do not need to specify the path to import
Node.js core modules or NPM modules in the require() function.
Monica Deshmane(H.V.Desai College,Pune) 19
• The exports is an object. So, you can
attach properties or methods to it.
The following example exposes an object with
a string property in Message.js file.
• Message.js
exports.SimpleMessage = 'Hello world';
//or
module.exports.SimpleMessage = 'Hello world';
• In the above example, we have attached a property Simple
Message to the exports object.
• Now, import and use this module, as shown below.
• app.js
var msg = require('./Messages.js');
console.log(msg.SimpleMessage);
Monica Deshmane(H.V.Desai College,Pune)
20
Export Object
• In the above example, the require() function
will return an object
{ SimpleMessage : 'Hello World'} and assign it
to the msg variable.
So, now you can use msg.SimpleMessage.
• Run the above example by writing node app.js in the
command prompt and see the output below.
• C:> node app.js
Hello World
• In the same way as above, you can expose an object
with function. The following example exposes an
object with the log function as a module.
Monica Deshmane(H.V.Desai College,Pune)
21
Export Object
• Log.js
module.exports.log = function (msg)
{ console.log(msg); };
• The above module will expose an object-
• { log : function(msg){ console.log(msg); } } .
• Use the above module as shown below.
• app.js
var msg = require('./Log.js');
msg.log('Hello World');
• Run and see the output in command prompt as shown
below.
• C:> node app.js
Hello World
Monica Deshmane(H.V.Desai College,Pune)
22
Export Object
Export Object continue...
• You can also attach an object to
module.exports, as shown below.
• data.js
module.exports = {
firstName: 'James',
lastName: 'Bond'
}
• app.js
var person = require('./data.js');
console.log(person.firstName + ' ' +
person.lastName);
• Run and see the result, as shown below.
• C:> node app.js
James Bond
Monica Deshmane(H.V.Desai College,Pune) 23
Export Function
• You can attach an anonymous function to
exports object as shown below.
• Log.js
module.exports = function (msg) { console.log(msg); };
• Now, you can use the above module, as shown below.
• app.js
• var msg = require('./Log.js');
msg('Hello World');
• The msg variable becomes a function expression in the above
example.
• So, you can invoke the function using parenthesis ( ).
• Run the above example and see the output.
• C:> node app.js
Hello World
Monica Deshmane(H.V.Desai College,Pune) 24
Export Function as a Class
• In JavaScript, a function can be treated like
a class.
• The following example exposes a function that
can be used like a class.
• Person.js
module.exports = function (firstName, lastName)
{
this.firstName = firstName;
this.lastName = lastName;
this.fullName = function ()
{ return this.firstName + ' ' + this.lastName; }
}
• The above module can be used, as shown below.
Monica Deshmane(H.V.Desai College,Pune)
25
Export Function as a Class
• app.js
var person = require('./Person.js');
var person1 = new person('James', 'Bond');
console.log(person1.fullName());
//console.log(person1);
• As you can see, we have created a person object using
the new keyword.
• Run the above example, as shown below.
• C:> node app.js
James Bond
//see output
• In this way, you can export and import a local module created
in a separate file under root folder.
• Node.js also allows you to create modules in sub folders. Let's
see how to load module from sub folders.
Monica Deshmane(H.V.Desai College,Pune)
26
Questions…
1. What is function?How to write functions in node
js?explain with example.
2. What happens if too few parameters or too
many parameters passed to function?
3. Explain what is module?also explain core & local
modules in brief with example.
4. Create own local module to display
concatenation of 2 strings passed from another
module.
5. How to export variable,function,array,object &
class ?Explain each with example.
Monica Deshmane(H.V.Desai College,Pune) 27
1mark questions-
1. What are the types of module in node js?
2. What is require()?
3. How to expose module?
4. Give structure of module?what it contains?
Monica Deshmane(H.V.Desai College,Pune) 28
29
Monica Deshmane(H.V.Desai College,Pune)
Questions?
Ad

More Related Content

What's hot (20)

JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Jquery
JqueryJquery
Jquery
Girish Srivastava
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
Edureka!
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
Yuriy Bezgachnyuk
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
Sergey Romaneko
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
WebStackAcademy
 
Vue.js
Vue.jsVue.js
Vue.js
Jadson Santos
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
Yao Nien Chung
 
jQuery
jQueryjQuery
jQuery
Jay Poojara
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
Shlomi Komemi
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
WebStackAcademy
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Joseph de Castelnau
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
sentayehu
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
Edureka!
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
WebStackAcademy
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
Yao Nien Chung
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
WebStackAcademy
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
sentayehu
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 

Similar to Nodejs functions & modules (20)

NodeJs Modules1.pdf
NodeJs Modules1.pdfNodeJs Modules1.pdf
NodeJs Modules1.pdf
Bareen Shaikh
 
NodeJs Session02
NodeJs Session02NodeJs Session02
NodeJs Session02
Jainul Musani
 
Requiring your own files.pptx
Requiring your own files.pptxRequiring your own files.pptx
Requiring your own files.pptx
Lovely Professional University
 
Packing for the Web with Webpack
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with Webpack
Thiago Temple
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
Jonathan Fine
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
rani marri
 
React Basic and Advance || React Basic
React Basic and Advance   || React BasicReact Basic and Advance   || React Basic
React Basic and Advance || React Basic
rafaqathussainc077
 
AJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfAJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdf
SreeVani74
 
Group111
Group111Group111
Group111
Shahriar Robbani
 
introduction_OOP for the java courses [Autosaved].pptx
introduction_OOP for the java courses [Autosaved].pptxintroduction_OOP for the java courses [Autosaved].pptx
introduction_OOP for the java courses [Autosaved].pptx
DrShamimAlMamun
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
Ivano Malavolta
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
cacois
 
JS & NodeJS - An Introduction
JS & NodeJS - An IntroductionJS & NodeJS - An Introduction
JS & NodeJS - An Introduction
Nirvanic Labs
 
2. Introduction to Java for engineering stud
2. Introduction to Java for engineering stud2. Introduction to Java for engineering stud
2. Introduction to Java for engineering stud
vyshukodumuri
 
JavaScript
JavaScriptJavaScript
JavaScript
Ivano Malavolta
 
object oriented programming unit one ppt
object oriented programming unit one pptobject oriented programming unit one ppt
object oriented programming unit one ppt
isiagnel2
 
IWT presentation121232112122222225556+556.pptx
IWT presentation121232112122222225556+556.pptxIWT presentation121232112122222225556+556.pptx
IWT presentation121232112122222225556+556.pptx
dgfs55437
 
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Roman Zenner
 
JS Essence
JS EssenceJS Essence
JS Essence
Uladzimir Piatryka
 
[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS
Ivano Malavolta
 
Packing for the Web with Webpack
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with Webpack
Thiago Temple
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
Jonathan Fine
 
React Basic and Advance || React Basic
React Basic and Advance   || React BasicReact Basic and Advance   || React Basic
React Basic and Advance || React Basic
rafaqathussainc077
 
AJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfAJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdf
SreeVani74
 
introduction_OOP for the java courses [Autosaved].pptx
introduction_OOP for the java courses [Autosaved].pptxintroduction_OOP for the java courses [Autosaved].pptx
introduction_OOP for the java courses [Autosaved].pptx
DrShamimAlMamun
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
cacois
 
JS & NodeJS - An Introduction
JS & NodeJS - An IntroductionJS & NodeJS - An Introduction
JS & NodeJS - An Introduction
Nirvanic Labs
 
2. Introduction to Java for engineering stud
2. Introduction to Java for engineering stud2. Introduction to Java for engineering stud
2. Introduction to Java for engineering stud
vyshukodumuri
 
object oriented programming unit one ppt
object oriented programming unit one pptobject oriented programming unit one ppt
object oriented programming unit one ppt
isiagnel2
 
IWT presentation121232112122222225556+556.pptx
IWT presentation121232112122222225556+556.pptxIWT presentation121232112122222225556+556.pptx
IWT presentation121232112122222225556+556.pptx
dgfs55437
 
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung für Magento, OXID eShop und Shopware (2013)
Roman Zenner
 
[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS[2015/2016] Require JS and Handlebars JS
[2015/2016] Require JS and Handlebars JS
Ivano Malavolta
 
Ad

More from monikadeshmane (20)

File system node js
File system node jsFile system node js
File system node js
monikadeshmane
 
Nodejs buffers
Nodejs buffersNodejs buffers
Nodejs buffers
monikadeshmane
 
Intsllation & 1st program nodejs
Intsllation & 1st program nodejsIntsllation & 1st program nodejs
Intsllation & 1st program nodejs
monikadeshmane
 
Nodejs basics
Nodejs basicsNodejs basics
Nodejs basics
monikadeshmane
 
Chap 5 php files part-2
Chap 5 php files   part-2Chap 5 php files   part-2
Chap 5 php files part-2
monikadeshmane
 
Chap 5 php files part 1
Chap 5 php files part 1Chap 5 php files part 1
Chap 5 php files part 1
monikadeshmane
 
Chap4 oop class (php) part 2
Chap4 oop class (php) part 2Chap4 oop class (php) part 2
Chap4 oop class (php) part 2
monikadeshmane
 
Chap4 oop class (php) part 1
Chap4 oop class (php) part 1Chap4 oop class (php) part 1
Chap4 oop class (php) part 1
monikadeshmane
 
Chap 3php array part4
Chap 3php array part4Chap 3php array part4
Chap 3php array part4
monikadeshmane
 
Chap 3php array part 3
Chap 3php array part 3Chap 3php array part 3
Chap 3php array part 3
monikadeshmane
 
Chap 3php array part 2
Chap 3php array part 2Chap 3php array part 2
Chap 3php array part 2
monikadeshmane
 
Chap 3php array part1
Chap 3php array part1Chap 3php array part1
Chap 3php array part1
monikadeshmane
 
PHP function
PHP functionPHP function
PHP function
monikadeshmane
 
php string part 4
php string part 4php string part 4
php string part 4
monikadeshmane
 
php string part 3
php string part 3php string part 3
php string part 3
monikadeshmane
 
php string-part 2
php string-part 2php string-part 2
php string-part 2
monikadeshmane
 
PHP string-part 1
PHP string-part 1PHP string-part 1
PHP string-part 1
monikadeshmane
 
java script
java scriptjava script
java script
monikadeshmane
 
ip1clientserver model
 ip1clientserver model ip1clientserver model
ip1clientserver model
monikadeshmane
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)
monikadeshmane
 
Ad

Recently uploaded (20)

ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 

Nodejs functions & modules

  • 1. Web Frameworks Node JS functions & Modules 1 Monica Deshmane(H.V.Desai College,Pune)
  • 2. Topics • Functions • Module and Module Types • Core Module, Local Module • Directories as module • Module.exports Monica Deshmane(H.V.Desai College,Pune) 2
  • 3. Functions »JavaScript is a functional programming language »A normal function structure in JavaScript is defined as follows. • function functionName() { // function body // optional return; } 3 Monica Deshmane(H.V.Desai College,Pune)
  • 4. Functions –All functions return a value in JavaScript. –If no explicit return statement, a function returns undefined. function myData() { return 123; } console.log(myData()); // 123 function myValue() { } console.log(myValue()); // undefined 4 Monica Deshmane(H.V.Desai College,Pune)
  • 5. Functions continue... • create a function: function hello(name) { console.log("hello " + name); } hello(“John"); • To declare parameters for a function in JavaScript, list them in the parentheses. • There is no checking of these parameters at runtime: function hello(name) { console.log("hello " + name); } hello(); //hello undefined 5 Monica Deshmane(H.V.Desai College,Pune)
  • 6. Functions continue... hello("CSS", "HTML", "AAA", 4); //hello CSS • If less parameters passed to function others are of type undefined. • If too many are passed extras are simply unused. • All functions have a predefined array in the body called arguments. 6 Monica Deshmane(H.V.Desai College,Pune)
  • 7. Functions continue... Functions in JavaScript with no names called anonymous functions. • var x = function (a, b) { return a + b; } • console.log(x(10, 20)); 7 Monica Deshmane(H.V.Desai College,Pune)
  • 8. Functions continue... Function Scope • Every time a function is called, a new variable scope is created. • Variables declared in the parent scope are available to that function. var pet = 'cat'; function myMethod() { var pet = 'dog'; console.log(pet); //dog } myMethod(); console.log(pet); //cat 8 Monica Deshmane(H.V.Desai College,Pune)
  • 9. Module and Module Types Node.js Module • Module in Node.js is functions in single or multiple JavaScript files for reusability. • Each module in Node.js has its own context, so it cannot interfere with other modules • Also, each module can be placed in a separate .js file under a separate folder. Monica Deshmane(H.V.Desai College,Pune) 9
  • 10. Module and Module Types Node.js Module Types Node.js includes three types of modules: 1. Core Modules 2. Local Modules 3. Third Party Modules Monica Deshmane(H.V.Desai College,Pune) 10
  • 11. 1)Local/own Modules • Create Your Own Modules Create a module that returns the current date and time: exports.myDateTime = function () { return Date(); }; • Use the exports keyword to make properties and methods available outside the module file. Save the code above in a file called "myfirstmodule.js" Monica Deshmane(H.V.Desai College,Pune) 11
  • 12. Own Modules • Include Your Own Module Use the module "myfirstmodule" in a Node.js file: var http = require('http'); var dt = require('./myfirstmodule'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write("The date and time are currently: " + dt.myDateTime()); res.end(); }).listen(8080); Monica Deshmane(H.V.Desai College,Pune) 12
  • 13. 2)Node.js Core/ built in Modules  Core Module & its Description • http - http module includes classes, methods and events to create Node.js http server. • url - url module includes methods for URL resolution and parsing. • Querystring-querystring module includes methods to deal with query string. • Path - path module includes methods to deal with file paths. • Fs - fs module includes classes, methods, and events to work with file I/O. • Util - util module includes utility functions useful for programmers. Monica Deshmane(H.V.Desai College,Pune) 13
  • 14. Loading Core Modules • In order to use Node.js core or NPM modules, you first need to import it using require() function as shown below. var module = require('module_name'); Monica Deshmane(H.V.Desai College,Pune) 14
  • 15. Loading Core Modules Example: Load and Use Core http Module var http = require('http'); var server = http.createServer(function(req, res) { //write code here } ); server.listen(5000); Monica Deshmane(H.V.Desai College,Pune) 15
  • 16. Directories as module • Folders as Modules# • There are ways in which a folder may be passed to require() as an argument. • The first is to create a package.json file in the root of the folder, which specifies a main module. • An example package.json file might look like this: { "name" : "some-library", "main" : "./lib/some-library.js" } Monica Deshmane(H.V.Desai College,Pune) 16
  • 17. Module.exports OR Export Module in Node.js • Here, you will learn how to expose different types as a module using module.exports. • The module.exports is a special object which is included in every JavaScript file in the Node.js application by default. • The module is a variable that represents the current module, and exports is an object that will be exposed as a module. • So, whatever you assign to module.exports will be exposed as a module. • Let's see how to expose different types as a module using module.exports. Monica Deshmane(H.V.Desai College,Pune) 17
  • 18. Module.exports / Export Module in Node.js • Export Literals • As mentioned above, exports is an object. So it exposes whatever you assigned to it as a module. • For example, if you assign a string literal then it will expose that string literal as a module. • The following example exposes simple string message as a module in Message.js. • Message.js module.exports = “Hello world”; • Now, import this message module and use it as shown below. Monica Deshmane(H.V.Desai College,Pune) 18
  • 19. Module.exports / Export Module in Node.js • app.js var msg = require('./Messages.js'); console.log(msg); • Run the above example and see the result, as shown below. • C:> node app.js Hello World node app.js Hello World • Note:You must specify ./ as a path of root folder to import a local module. • However, you do not need to specify the path to import Node.js core modules or NPM modules in the require() function. Monica Deshmane(H.V.Desai College,Pune) 19
  • 20. • The exports is an object. So, you can attach properties or methods to it. The following example exposes an object with a string property in Message.js file. • Message.js exports.SimpleMessage = 'Hello world'; //or module.exports.SimpleMessage = 'Hello world'; • In the above example, we have attached a property Simple Message to the exports object. • Now, import and use this module, as shown below. • app.js var msg = require('./Messages.js'); console.log(msg.SimpleMessage); Monica Deshmane(H.V.Desai College,Pune) 20 Export Object
  • 21. • In the above example, the require() function will return an object { SimpleMessage : 'Hello World'} and assign it to the msg variable. So, now you can use msg.SimpleMessage. • Run the above example by writing node app.js in the command prompt and see the output below. • C:> node app.js Hello World • In the same way as above, you can expose an object with function. The following example exposes an object with the log function as a module. Monica Deshmane(H.V.Desai College,Pune) 21 Export Object
  • 22. • Log.js module.exports.log = function (msg) { console.log(msg); }; • The above module will expose an object- • { log : function(msg){ console.log(msg); } } . • Use the above module as shown below. • app.js var msg = require('./Log.js'); msg.log('Hello World'); • Run and see the output in command prompt as shown below. • C:> node app.js Hello World Monica Deshmane(H.V.Desai College,Pune) 22 Export Object
  • 23. Export Object continue... • You can also attach an object to module.exports, as shown below. • data.js module.exports = { firstName: 'James', lastName: 'Bond' } • app.js var person = require('./data.js'); console.log(person.firstName + ' ' + person.lastName); • Run and see the result, as shown below. • C:> node app.js James Bond Monica Deshmane(H.V.Desai College,Pune) 23
  • 24. Export Function • You can attach an anonymous function to exports object as shown below. • Log.js module.exports = function (msg) { console.log(msg); }; • Now, you can use the above module, as shown below. • app.js • var msg = require('./Log.js'); msg('Hello World'); • The msg variable becomes a function expression in the above example. • So, you can invoke the function using parenthesis ( ). • Run the above example and see the output. • C:> node app.js Hello World Monica Deshmane(H.V.Desai College,Pune) 24
  • 25. Export Function as a Class • In JavaScript, a function can be treated like a class. • The following example exposes a function that can be used like a class. • Person.js module.exports = function (firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.fullName = function () { return this.firstName + ' ' + this.lastName; } } • The above module can be used, as shown below. Monica Deshmane(H.V.Desai College,Pune) 25
  • 26. Export Function as a Class • app.js var person = require('./Person.js'); var person1 = new person('James', 'Bond'); console.log(person1.fullName()); //console.log(person1); • As you can see, we have created a person object using the new keyword. • Run the above example, as shown below. • C:> node app.js James Bond //see output • In this way, you can export and import a local module created in a separate file under root folder. • Node.js also allows you to create modules in sub folders. Let's see how to load module from sub folders. Monica Deshmane(H.V.Desai College,Pune) 26
  • 27. Questions… 1. What is function?How to write functions in node js?explain with example. 2. What happens if too few parameters or too many parameters passed to function? 3. Explain what is module?also explain core & local modules in brief with example. 4. Create own local module to display concatenation of 2 strings passed from another module. 5. How to export variable,function,array,object & class ?Explain each with example. Monica Deshmane(H.V.Desai College,Pune) 27
  • 28. 1mark questions- 1. What are the types of module in node js? 2. What is require()? 3. How to expose module? 4. Give structure of module?what it contains? Monica Deshmane(H.V.Desai College,Pune) 28
  翻译: