SlideShare a Scribd company logo
1 of 38
Node.js Fundamentals
Node.js Modules
In Node.js, Modules are the blocks of encapsulated code that
communicates with an external application on the basis of their related
functionality. Modules can be a single file or a collection of multiples
files/folders. The reason programmers are heavily reliant on modules is
because of their re-usability as well as the ability to break down a
complex piece of code into manageable chunks.
Modules are of three types:
• Core Modules Built-in Module ( installation)
• Local Modules: used defined module
• Third-party Modules
Core Modules
Node.js has many built-in modules that are part of the platform and
comes with Node.js installation. These modules can be loaded into the
program by using the require function.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Welcome to this page!');
res.end();
}).listen(8080);
Which function of Node.js module is used to
create an HTTP server?
The http module is a core module of Node designed to support many
features of the HTTP protocol.
1. createServer()
Local Modules
Unlike built-in and external modules, local modules are created locally
in your Node.js application.
Create Your Own Modules
You can create your own modules, and easily include them in your
applications. The following example creates a module that returns a date
and time object:
Example: 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".
Include Your Own Module
Now you can include and use the module in any of your Node.js files.
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);
Notice that we use ./ to locate the module, that means that the module is
located in the same folder as the Node.js file.
Save the code above in a file called "demo_module.js", and initiate the
file.
http://localhost:8080
Example to create own Module
Let’s create a simple calculating module that calculates various
operations. Create a calc.js file that has the following code:
exports.add = function (x, y) { return x + y; };
exports.sub = function (x, y) { return x - y; };
exports.mult = function (x, y) { return x * y; };
exports.div = function (x, y) { return x / y; };
// Save the file with File name: calc.js
Include Your Own Module
var http = require('http');
var calculator = require('./calc');
var x = 50, y = 20;
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("Addition of 50 and 20 is " + calculator.add(x, y) + '<br/>');
res.write("Subtraction of 50 and 20 is " + calculator.sub(x, y) + '<br/>');
res.write("Multiplication of 50 and 20 is " + calculator.mult(x, y) + '<br/>');
res.write("Division of 50 and 20 is " + calculator.div(x, y));
res.end();
}).listen(8080);
// Save the file with File name: App.js
Simple logging module which logs the information,
warning or error to the console
var log = { // Message.js
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
};
module.exports = log
Loading Local Module
var myLogModule = require(‘./Message.js’);
myLogModule.info('Node.js started');
myLogModule.error('Node.js not started and have an error');
myLogModule.warning('Node.js is started with a warning message');
Export Module in Node.js
Export Literals
module.exports = 'Hello world'; // message.js
Now, import this message module and use it as shown below.
var msg = require('./Messages.js’); //app.js
console.log(msg);
Export Object
• exports.SimpleMessage = 'Hello world'; // Message.js
//or
• module.exports.SimpleMessage = 'Hello world';
• In the above example, we have attached a property SimpleMessage to
the exports object. Now, import and use this module, as shown below.
var msg = require('./Messages.js'); // app1.js
console.log(msg.SimpleMessage);
Question 2:
Which keyword you used to make properties and methods available
outside the module file?
• exports
Third-party Modules
Third-party modules are modules that are available online using the
Node Package Manager(NPM). These modules can be installed in the
project folder or globally. Some of the popular third-party modules are
mongoose, express, angular, and react.
Example:
• npm install upper-case
• npm install express
Example 1: npm install upper-case
var http = require('http');
var uc = require('upper-case');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(uc.upperCase("Hello World!"));
res.end();
}).listen(8080);
Node.js File System Module : fs
The Node.js file system module allows you to work with the file system
on your computer. To include the File System module, use the require()
method:
var fs = require('fs'); //
Common use for the File System Module:
1. Read files
2. Create files
3. Update files
4. Delete files
5. Rename files
The fs.readFile() method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder
as Node.js):
// demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
Create a Node.js file that reads the HTML file, and
return the content
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Save the code above in a file called "demo_readfile.js", and initiate the
file:
Initiate demo_readfile.js: C:UsersYour Name>node demo_readfile.js
If you have followed the same steps on your computer, you will see the
same result as the example:
http://localhost:8080
Create Files:
The File System module has methods for creating new files:
1. fs.appendFile()
2. fs.open()
3. fs.writeFile()
fs.appendFile():
The fs.appendFile() method appends specified content to a file. If the
file does not exist, the file will be created:
Create a new file using the appendFile() method:
// demo_fs_append.js
var fs = require('fs');
fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
fs.open():
The fs.open() method takes a "flag" as the second argument, if the flag is
"w" for "writing", the specified file is opened for writing. If the file does
not exist, an empty file is created. Create a new, empty file using the
open() method:
// demo_fs_open.js
var fs = require('fs');
fs.open('mynewfile2.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
});
fs.writeFile():
The fs.writeFile() method replaces the specified file and content if it
exists. If the file does not exist, a new file, containing the specified
content, will be created:
// demo_fs_writefile.js
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
Update Files
The File System module has methods for updating files:
1. fs.appendFile()
2. fs.writeFile()
fs.appendFile()
The fs.appendFile() method appends the specified content at the end of
the specified file:
// demo_fs_update.js
var fs = require('fs');
fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) {
if (err) throw err;
console.log('Updated!');
});
fs.writeFile()
The fs.writeFile() method replaces the specified file and content:
// demo_fs_replace.js
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Replaced!');
});
Delete Files
To delete a file with the File System module, use the fs.unlink()
method. The fs.unlink() method deletes the specified file:
// demo_fs_unlink.js
var fs = require('fs');
fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
Rename Files
To rename a file with the File System module, use the fs.rename()
method. The fs.rename() method renames the specified file:
// demo_fs_rename.js
var fs = require('fs');
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
});,
Question for Poll:
1) Which of the following statement is correct?
1. js is Server Side Language.
2. Js is the Client Side Language.
3. js is both Server Side and Client Side Language.
4. None of the above.
2) Which of the following command is used to install the Node.js
express module?
1. $ npm install express
2. $ node install express
3. $ install express
4. None of the above
3) What is Callback?
1. The callback is a technique in which a method calls back the caller
method.
2. The callback is an asynchronous equivalent for a function.
3. Both of the above.
4. None of the above.
4) Which of the following extension is used to save the Node.js files?
1. .js
2. .node
3. .java
4. .txt
5) The Node.js modules can be exposed using:
1. expose
2. module
3. exports
4. All of the above
6) What does the fs module stand for?
1. File Service
2. File System
3. File Store
4. File Sharing
7) What is the default scope in the Node.js application?
1. Global
2. Local
3. Global Function
4. Local to object
8) Which of the following statement is used to execute the code of the
sample.js file?
1. sample.js
2. node sample.js
3. nodejs sample.js
4. None of the above.

More Related Content

Similar to Requiring your own files.pptx

Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modulesmonikadeshmane
 
Best Practices For Direct Admin Security
Best Practices For Direct Admin SecurityBest Practices For Direct Admin Security
Best Practices For Direct Admin Securitylisa Dsouza
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android Aakash Ugale
 
Tips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxTips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxAgusto Sipahutar
 
NodeJs
NodeJsNodeJs
NodeJsdizabl
 
Serving Moodle Presentation
Serving Moodle PresentationServing Moodle Presentation
Serving Moodle Presentationwebhostingguy
 
Nodejs quick start
Nodejs quick startNodejs quick start
Nodejs quick startGuangyao Cao
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applicationsjeromevdl
 
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and ToolingSencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and ToolingSencha
 
Packing for the Web with Webpack
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with WebpackThiago Temple
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event EmittersTheCreativedev Blog
 
Joomla Beginner Template Presentation
Joomla Beginner Template PresentationJoomla Beginner Template Presentation
Joomla Beginner Template Presentationalledia
 

Similar to Requiring your own files.pptx (20)

Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 
Best Practices For Direct Admin Security
Best Practices For Direct Admin SecurityBest Practices For Direct Admin Security
Best Practices For Direct Admin Security
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
 
Browserify
BrowserifyBrowserify
Browserify
 
Php
PhpPhp
Php
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
 
RequireJS
RequireJSRequireJS
RequireJS
 
Tips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxTips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptx
 
NodeJs
NodeJsNodeJs
NodeJs
 
Serving Moodle Presentation
Serving Moodle PresentationServing Moodle Presentation
Serving Moodle Presentation
 
Nodejs quick start
Nodejs quick startNodejs quick start
Nodejs quick start
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
 
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and ToolingSencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
Packing for the Web with Webpack
Packing for the Web with WebpackPacking for the Web with Webpack
Packing for the Web with Webpack
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
Joomla Beginner Template Presentation
Joomla Beginner Template PresentationJoomla Beginner Template Presentation
Joomla Beginner Template Presentation
 
Creating a basic joomla
Creating a basic joomlaCreating a basic joomla
Creating a basic joomla
 

More from Lovely Professional University

The HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageThe HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageLovely Professional University
 

More from Lovely Professional University (20)

The HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageThe HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup language
 
Working with JSON
Working with JSONWorking with JSON
Working with JSON
 
Yargs Module
Yargs ModuleYargs Module
Yargs Module
 
NODEMON Module
NODEMON ModuleNODEMON Module
NODEMON Module
 
Getting Input from User
Getting Input from UserGetting Input from User
Getting Input from User
 
fs Module.pptx
fs Module.pptxfs Module.pptx
fs Module.pptx
 
Transaction Processing in DBMS.pptx
Transaction Processing in DBMS.pptxTransaction Processing in DBMS.pptx
Transaction Processing in DBMS.pptx
 
web_server_browser.ppt
web_server_browser.pptweb_server_browser.ppt
web_server_browser.ppt
 
Web Server.pptx
Web Server.pptxWeb Server.pptx
Web Server.pptx
 
Number System.pptx
Number System.pptxNumber System.pptx
Number System.pptx
 
Programming Language.ppt
Programming Language.pptProgramming Language.ppt
Programming Language.ppt
 
Information System.pptx
Information System.pptxInformation System.pptx
Information System.pptx
 
Applications of Computer Science in Pharmacy-1.pptx
Applications of Computer Science in Pharmacy-1.pptxApplications of Computer Science in Pharmacy-1.pptx
Applications of Computer Science in Pharmacy-1.pptx
 
Application of Computers in Pharmacy.pptx
Application of Computers in Pharmacy.pptxApplication of Computers in Pharmacy.pptx
Application of Computers in Pharmacy.pptx
 
Deploying your app.pptx
Deploying your app.pptxDeploying your app.pptx
Deploying your app.pptx
 
Setting up github and ssh keys.ppt
Setting up github and ssh keys.pptSetting up github and ssh keys.ppt
Setting up github and ssh keys.ppt
 
Adding a New Feature and Deploying.ppt
Adding a New Feature and Deploying.pptAdding a New Feature and Deploying.ppt
Adding a New Feature and Deploying.ppt
 
Unit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptxUnit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptx
 
Yargs Module.pptx
Yargs Module.pptxYargs Module.pptx
Yargs Module.pptx
 
Working with JSON.pptx
Working with JSON.pptxWorking with JSON.pptx
Working with JSON.pptx
 

Recently uploaded

Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxMustafa Ahmed
 
Introduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxIntroduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxhublikarsn
 
Introduction to Geographic Information Systems
Introduction to Geographic Information SystemsIntroduction to Geographic Information Systems
Introduction to Geographic Information SystemsAnge Felix NSANZIYERA
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...josephjonse
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 
8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessorAshwiniTodkar4
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxSCMS School of Architecture
 
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...ssuserdfc773
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwaitjaanualu31
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...drmkjayanthikannan
 
Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...ppkakm
 
Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)ChandrakantDivate1
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARKOUSTAV SARKAR
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...Amil baba
 
Post office management system project ..pdf
Post office management system project ..pdfPost office management system project ..pdf
Post office management system project ..pdfKamal Acharya
 

Recently uploaded (20)

Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptx
 
Introduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxIntroduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptx
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Introduction to Geographic Information Systems
Introduction to Geographic Information SystemsIntroduction to Geographic Information Systems
Introduction to Geographic Information Systems
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...Basic Electronics for diploma students as per technical education Kerala Syll...
Basic Electronics for diploma students as per technical education Kerala Syll...
 
Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
Post office management system project ..pdf
Post office management system project ..pdfPost office management system project ..pdf
Post office management system project ..pdf
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 

Requiring your own files.pptx

  • 2. Node.js Modules In Node.js, Modules are the blocks of encapsulated code that communicates with an external application on the basis of their related functionality. Modules can be a single file or a collection of multiples files/folders. The reason programmers are heavily reliant on modules is because of their re-usability as well as the ability to break down a complex piece of code into manageable chunks. Modules are of three types: • Core Modules Built-in Module ( installation) • Local Modules: used defined module • Third-party Modules
  • 3. Core Modules Node.js has many built-in modules that are part of the platform and comes with Node.js installation. These modules can be loaded into the program by using the require function. var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write('Welcome to this page!'); res.end(); }).listen(8080);
  • 4. Which function of Node.js module is used to create an HTTP server? The http module is a core module of Node designed to support many features of the HTTP protocol. 1. createServer()
  • 5. Local Modules Unlike built-in and external modules, local modules are created locally in your Node.js application.
  • 6. Create Your Own Modules You can create your own modules, and easily include them in your applications. The following example creates a module that returns a date and time object: Example: 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".
  • 7. Include Your Own Module Now you can include and use the module in any of your Node.js files. 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);
  • 8. Notice that we use ./ to locate the module, that means that the module is located in the same folder as the Node.js file. Save the code above in a file called "demo_module.js", and initiate the file. http://localhost:8080
  • 9. Example to create own Module Let’s create a simple calculating module that calculates various operations. Create a calc.js file that has the following code: exports.add = function (x, y) { return x + y; }; exports.sub = function (x, y) { return x - y; }; exports.mult = function (x, y) { return x * y; }; exports.div = function (x, y) { return x / y; }; // Save the file with File name: calc.js
  • 10. Include Your Own Module var http = require('http'); var calculator = require('./calc'); var x = 50, y = 20; http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write("Addition of 50 and 20 is " + calculator.add(x, y) + '<br/>'); res.write("Subtraction of 50 and 20 is " + calculator.sub(x, y) + '<br/>'); res.write("Multiplication of 50 and 20 is " + calculator.mult(x, y) + '<br/>'); res.write("Division of 50 and 20 is " + calculator.div(x, y)); res.end(); }).listen(8080); // Save the file with File name: App.js
  • 11. Simple logging module which logs the information, warning or error to the console var log = { // Message.js info: function (info) { console.log('Info: ' + info); }, warning:function (warning) { console.log('Warning: ' + warning); }, error:function (error) { console.log('Error: ' + error); } }; module.exports = log
  • 12. Loading Local Module var myLogModule = require(‘./Message.js’); myLogModule.info('Node.js started'); myLogModule.error('Node.js not started and have an error'); myLogModule.warning('Node.js is started with a warning message');
  • 13. Export Module in Node.js Export Literals module.exports = 'Hello world'; // message.js Now, import this message module and use it as shown below. var msg = require('./Messages.js’); //app.js console.log(msg);
  • 14. Export Object • exports.SimpleMessage = 'Hello world'; // Message.js //or • module.exports.SimpleMessage = 'Hello world'; • In the above example, we have attached a property SimpleMessage to the exports object. Now, import and use this module, as shown below. var msg = require('./Messages.js'); // app1.js console.log(msg.SimpleMessage);
  • 15. Question 2: Which keyword you used to make properties and methods available outside the module file? • exports
  • 16. Third-party Modules Third-party modules are modules that are available online using the Node Package Manager(NPM). These modules can be installed in the project folder or globally. Some of the popular third-party modules are mongoose, express, angular, and react. Example: • npm install upper-case • npm install express
  • 17. Example 1: npm install upper-case var http = require('http'); var uc = require('upper-case'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(uc.upperCase("Hello World!")); res.end(); }).listen(8080);
  • 18. Node.js File System Module : fs The Node.js file system module allows you to work with the file system on your computer. To include the File System module, use the require() method: var fs = require('fs'); // Common use for the File System Module: 1. Read files 2. Create files 3. Update files 4. Delete files 5. Rename files
  • 19. The fs.readFile() method is used to read files on your computer. Assume we have the following HTML file (located in the same folder as Node.js): // demofile1.html <html> <body> <h1>My Header</h1> <p>My paragraph.</p> </body> </html>
  • 20. Create a Node.js file that reads the HTML file, and return the content var http = require('http'); var fs = require('fs'); http.createServer(function (req, res) { fs.readFile('demofile1.html', function(err, data) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); return res.end(); }); }).listen(8080);
  • 21. Save the code above in a file called "demo_readfile.js", and initiate the file: Initiate demo_readfile.js: C:UsersYour Name>node demo_readfile.js If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080
  • 22. Create Files: The File System module has methods for creating new files: 1. fs.appendFile() 2. fs.open() 3. fs.writeFile()
  • 23. fs.appendFile(): The fs.appendFile() method appends specified content to a file. If the file does not exist, the file will be created: Create a new file using the appendFile() method: // demo_fs_append.js var fs = require('fs'); fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) { if (err) throw err; console.log('Saved!'); });
  • 24. fs.open(): The fs.open() method takes a "flag" as the second argument, if the flag is "w" for "writing", the specified file is opened for writing. If the file does not exist, an empty file is created. Create a new, empty file using the open() method: // demo_fs_open.js var fs = require('fs'); fs.open('mynewfile2.txt', 'w', function (err, file) { if (err) throw err; console.log('Saved!'); });
  • 25. fs.writeFile(): The fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a new file, containing the specified content, will be created: // demo_fs_writefile.js var fs = require('fs'); fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) { if (err) throw err; console.log('Saved!'); });
  • 26. Update Files The File System module has methods for updating files: 1. fs.appendFile() 2. fs.writeFile()
  • 27. fs.appendFile() The fs.appendFile() method appends the specified content at the end of the specified file: // demo_fs_update.js var fs = require('fs'); fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) { if (err) throw err; console.log('Updated!'); });
  • 28. fs.writeFile() The fs.writeFile() method replaces the specified file and content: // demo_fs_replace.js var fs = require('fs'); fs.writeFile('mynewfile3.txt', 'This is my text', function (err) { if (err) throw err; console.log('Replaced!'); });
  • 29. Delete Files To delete a file with the File System module, use the fs.unlink() method. The fs.unlink() method deletes the specified file: // demo_fs_unlink.js var fs = require('fs'); fs.unlink('mynewfile2.txt', function (err) { if (err) throw err; console.log('File deleted!'); });
  • 30. Rename Files To rename a file with the File System module, use the fs.rename() method. The fs.rename() method renames the specified file: // demo_fs_rename.js var fs = require('fs'); fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) { if (err) throw err; console.log('File Renamed!'); });,
  • 31. Question for Poll: 1) Which of the following statement is correct? 1. js is Server Side Language. 2. Js is the Client Side Language. 3. js is both Server Side and Client Side Language. 4. None of the above.
  • 32. 2) Which of the following command is used to install the Node.js express module? 1. $ npm install express 2. $ node install express 3. $ install express 4. None of the above
  • 33. 3) What is Callback? 1. The callback is a technique in which a method calls back the caller method. 2. The callback is an asynchronous equivalent for a function. 3. Both of the above. 4. None of the above.
  • 34. 4) Which of the following extension is used to save the Node.js files? 1. .js 2. .node 3. .java 4. .txt
  • 35. 5) The Node.js modules can be exposed using: 1. expose 2. module 3. exports 4. All of the above
  • 36. 6) What does the fs module stand for? 1. File Service 2. File System 3. File Store 4. File Sharing
  • 37. 7) What is the default scope in the Node.js application? 1. Global 2. Local 3. Global Function 4. Local to object
  • 38. 8) Which of the following statement is used to execute the code of the sample.js file? 1. sample.js 2. node sample.js 3. nodejs sample.js 4. None of the above.