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?

More Related Content

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