Node.js Modules

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:

assertProvides a set of assertion tests
bufferTo handle binary data
child_processTo run a child process
clusterTo spla singlit e Node process into multiple processes
cryptoTo handle OpenSSL cryptographic functions
dgramProvides implementation of UDP data gram sockets
dnsTo do DNS lookup and name resolution functions
domainDeprecated. To handle unhanded errors
eventsTo handle events
fsTo handle the file system
httpTo make Node.js act as an HTTP server
httpsTo make Node.js act as an HTTPS server.
netTo create servers and clients
osProvides information about the operation system
pathTo handle file paths
punycodeDeprecated. A character encoding scheme
querystringTo handle URL query strings
readlineTo handle readable streams one line at the time
streamTo handle streaming data
string_decoderTo decode buffer objects into strings
timersTo execute a function after a given number of milliseconds
tlsTo implement TLS and SSL protocols
ttyProvides classes used by a text terminal
urlTo parse URL strings
utilTo access utility functions
v8To access information about V8 (the JavaScript engine)
vmTo compile JavaScript code in a virtual machine
zlibTo 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.

1 Comment

  1. Thanks for another wonderful post. Where else could anyone get that type of info in such an ideal way of writing? I have a presentation next week, and I’m on the look for such information.

Leave a Reply

Your email address will not be published.


*