0% found this document useful (0 votes)
9 views

3 5nodejs

- Node.js modules allow organizing code into reusable pieces. There are core modules, local modules, and third party modules. - Core modules are compiled directly into Node.js while local and third party modules must be loaded using require(). - A simple local module example creates a logging object with info, warning, and error functions and exports it so it can be required and used in other files.

Uploaded by

sahilahemad05
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

3 5nodejs

- Node.js modules allow organizing code into reusable pieces. There are core modules, local modules, and third party modules. - Core modules are compiled directly into Node.js while local and third party modules must be loaded using require(). - A simple local module example creates a logging object with info, warning, and error functions and exports it so it can be required and used in other files.

Uploaded by

sahilahemad05
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Node.

js Module
• Module in Node.js is a simple or complex
functionality organized in single or multiple
JavaScript files which can be reused throughout
the Node.js application.
• Each module in Node.js has its own context, so it
cannot interfere with other modules global scope.
Also, each module can be placed in a separate .js
file under a separate folder.
• Node.js implements CommonJS
modules standard. CommonJS is a group. who
define JavaScript standards for web server,
desktop, and console application.
• Node.js Module Types
• Node.js includes three types of modules:
• Core Modules
• Local Modules
• Third Party Modules
• Node.js Core Modules
• Node.js is a light weight framework.
• The core modules include minimum
functionalities of Node.js.
• These core modules are compiled into its
binary distribution and load automatically
when Node.js process starts.
• However, you need to import the core
module first in order to use it in your
application.
The following table lists some of the important core modules in Node.js.

Core Module 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.


• 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');
• As per above syntax, specify the module name in
the require() function. The require() function will
return an object, function, property or any other
JavaScript type, depending on what the specified
module returns.
• The following example demonstrates how to use
Node.js http module to create a web server.
• Example: Load and Use Core http Module Copy
• Example: Load and Use Core http Module Copy
• var http = require('http');

//create a server object:
• http.createServer(function (req, res) {
• res.write(‘Hi!'); //write a response to the client
• res.end(); //end the response
• }).listen(5000); //the server object listens on port 5000

link:http://localhost:5000/

• In the above example, require() function returns an object because http module
returns its functionality as an object, you can then use its properties and method
using dot notation e.g. http.createServer().
• In this way, you can load and use Node.js core modules in your application.
• Node.js Local Module
• Local modules are modules created locally in your
Node.js application.
• These modules include different functionalities of
your application in separate files and folders.
• You can also package it and distribute it via NPM,
so that the Node.js community can use it.
• For example, if you need to connect to MongoDB
and fetch data then you can create a module for
it, which can be reused in your application
• Writing Simple Module
• Let's write a simple logging module which logs
the information, warning or error to the
console.
• In Node.js, module should be placed in a
separate JavaScript file. So, create a Log.js file
and write the following code in it.
• Example Log.js
• var log = {
• info: function (info) {
• console.log('Info: ' + info);
• },
• warning:function (warning) {
• console.log('Warning: ' + warning);
• },
• error:function (error) {
• console.log('Error: ' + error);
• }
• };

• module.exports = log
• In the above example of logging module, we have created an
object with three functions - info(), warning() and error(). At
the end, we have assigned this object to module.exports. The
module.exports in the above example exposes a log object as a
module.
• The module.exports is a special object which is included in
every JS file in the Node.js application by default.
Use module.exports or exports to expose a function, object
or variable as a module in Node.js.
• Loading Local Module
• To use local modules in your application, you
need to load it using require() function in the
same way as core module.
• However, you need to specify the path of
JavaScript file of the module.
• The following example demonstrates how to use
the above logging module contained in Log.js.
• Example :app.js Copy
• var myLogModule = require('./Log.js');
myLogModule.info('Node.js started');
• In the above example, app.js is using log module. First,
it loads the logging module using require() function
and specified path where logging module is stored.
• Logging module is contained in Log.js file in the root
folder. So, we have specified the path './Log.js' in the
require() function. The '.' denotes a root folder.
• The require() function returns a log object because
logging module exposes an object in Log.js using
module.exports.
• So now you can use logging module as an object and
call any of its function using dot notation e.g
myLogModule.info() or myLogModule.warning() or
myLogModule.error()
• 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.
• Export
• 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
then it will expose that string as a module.
• The following example exposes simple string
message as a module in m.js.
• m.js Copy
• module.exports = 'Hello world';
• Now, import this message m and use it as
shown below.
• m22.js Copy
• var msg = require(‘./m.js’);
• console.log(msg);
• Run the above example and see the result, as
shown below.
• C:\> node m22.js
• Hello World
• Export Object
• 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.
• m3.js Copy
• exports.SimpleMessage = 'Hello world'; //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.
• m4.js Copy
• var msg = require(‘./m3.js'); console.log(msg.SimpleMessage);
• 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 as shown below.
What is a Web Server?
• Node.js is an open-source server environment.
Node.js uses JavaScript on the server. The task
of a web server is to open a file on the server
and return the content to the client.
• Node.js has a built-in module called HTTP,
which allows Node.js to transfer data over the
Hyper Text Transfer Protocol (HTTP). The
HTTP module can create an HTTP server that
listens to server ports and gives a response
back to the client.
Node.js web-based Example

• A node.js web application contains the following three


parts:
• Import required modules: The "require" directive is
used to load a Node.js module.
• Create server: You have to establish a server which will
listen to client's request similar to Apache HTTP Server.
• Read request and return response: Server created in
the second step will read HTTP request made by client
which can be a browser or console and return the
response.
• How to create node.js web applications
• Follow these steps:
• Import required module: The first step is to
use ?require? directive to load http module
and store returned HTTP instance into http
variable. For example:
• var http = require("http");
• Create server: In the second step, you have to
use created http instance and call
http.createServer() method to create server
instance and then bind it at port 8081 using
listen method associated with server instance.
Pass it a function with request and response
parameters and write the sample
implementation to return "Hello World". For
example:
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/
plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
Combine step1 and step2 together in a file named "main.js".
File: main.js

var http = require("http");


http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
How to start your server:
Go to start menu and click on the Node.js command
prompt.
Now command prompt is open:
Set path: Here we have save “server.js" file on the
desktop.
So type cd desktop on the command prompt. After that
execute the server.js to start the server as follows:
node main.js
Now server is started.
Make a request to Node.js server:
Open http://127.0.0.1:8081/ in any browser. You will see
the following result.

You might also like