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.

Requiring your own files.pptx

  • 1.
  • 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 hasmany 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 ofNode.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-inand external modules, local modules are created locally in your Node.js application.
  • 6.
    Create Your OwnModules 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 OwnModule 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 weuse ./ 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 createown 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 OwnModule 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 modulewhich 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 varmyLogModule = 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 inNode.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 keywordyou used to make properties and methods available outside the module file? • exports
  • 16.
    Third-party Modules Third-party modulesare 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: npminstall 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 SystemModule : 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() methodis 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.jsfile 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 codeabove 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 FileSystem module has methods for creating new files: 1. fs.appendFile() 2. fs.open() 3. fs.writeFile()
  • 23.
    fs.appendFile(): The fs.appendFile() methodappends 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() methodtakes 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() methodreplaces 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 FileSystem module has methods for updating files: 1. fs.appendFile() 2. fs.writeFile()
  • 27.
    fs.appendFile() The fs.appendFile() methodappends 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() methodreplaces 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 deletea 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 renamea 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 ofthe 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 isCallback? 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 ofthe following extension is used to save the Node.js files? 1. .js 2. .node 3. .java 4. .txt
  • 35.
    5) The Node.jsmodules can be exposed using: 1. expose 2. module 3. exports 4. All of the above
  • 36.
    6) What doesthe fs module stand for? 1. File Service 2. File System 3. File Store 4. File Sharing
  • 37.
    7) What isthe default scope in the Node.js application? 1. Global 2. Local 3. Global Function 4. Local to object
  • 38.
    8) Which ofthe 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.