What is a Module in Node.js?
A set of functions that you want to include in your application.
Built-in Modules
Node.js has a set of built-in modules that you can use without any further installation.
Examples:
assert | Provides a set of assertion tests |
buffer | To handle binary data |
child_process | To run a child process |
cluster | To spla singlit e Node process into multiple processes |
crypto | To handle OpenSSL cryptographic functions |
dgram | Provides implementation of UDP data gram sockets |
dns | To do DNS lookup and name resolution functions |
domain | Deprecated. To handle unhanded errors |
events | To handle events |
fs | To handle the file system |
http | To make Node.js act as an HTTP server |
https | To make Node.js act as an HTTPS server. |
net | To create servers and clients |
os | Provides information about the operation system |
path | To handle file paths |
punycode | Deprecated. A character encoding scheme |
querystring | To handle URL query strings |
readline | To handle readable streams one line at the time |
stream | To handle streaming data |
string_decoder | To decode buffer objects into strings |
timers | To execute a function after a given number of milliseconds |
tls | To implement TLS and SSL protocols |
tty | Provides classes used by a text terminal |
url | To parse URL strings |
util | To access utility functions |
v8 | To access information about V8 (the JavaScript engine) |
vm | To compile JavaScript code in a virtual machine |
zlib | To compress or decompress files |
How to Include Modules
To include a module, use the require()
function with the name of the module
Examples
var http = require(‘http‘);
var timers= require(‘timers‘);
Create Your Own Modules
You can create your own modules, and easily include them in your applications.
See the following example.
mydate.js
—————————————————————————————————
exports.myDateTime=function(){
return Date();
}
exports.myTime=function(){
var date=new Date();
return date.getHours()+”:”+date.getMinutes();
}
exports.myYear=function(){
var date=new Date();
return date.getFullYear();
}
exports.myMonth=function(){
var date=new Date();
return (date.getMonth()+1);
}
index.js
————————————————————————————————–
var http=require(‘http’);
var mydate=require(‘./mydate’);//here iclude my created module
http.createServer(
function (req,res){
var today=mydate.myDateTime();
res.write(“Today is:”+today+”\n”);
var now=mydate.myTime();
res.write(“Now time is:”+now+”\n”);
var year=mydate.myYear();
res.write(“Year is:”+year+”\n”);
var month=mydate.myMonth();
res.write(“Month is:”+month+”\n”);
res.end();
}
).listen(8080);
Use the exports
keyword to make properties and methods available outside the module file.