Menu Close

Node.js Modules

Codeamend

Here the tutorial for node module.,

What is a Module in Node.js?

Node modules same as JavaScript libraries. A set of functions which you want to include in your application.

Built-in Modules

Node.js has some set of built-in modules which we can use without any further installation.

Some basic built in modules are,

  • fs
  • http
  • https
  • path
  • url and etc

Include Modules

To include a module, you use the function require() with the name of the module:
var http = require('http'); 
Reference to access the HTTP module, and is able to create a server:
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('Hello Codeamend!');
}).listen(3000); 

Create Your Own Modules

Create your own modules, and easily include them in your applications. Following example creates a module that returns a date and time object:

Use the exports keyword to make properties and methods available outside the module file.

Save the code below in a file called “codedate.js”

exports.codeDate = function () {
  return Date();
}; 

Include Your Own Module

Include and use the module in any of your Node.js files. Create new file called “sample.js” and add below cods, and run the file: using node sample.js.

After that you can view the output in http://localhost:3000

Note: Keep both sample.js and codedate.js files in same folder.

var http = require('http');
var datetime = require('./codedate');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write("The date and time are currently: " + dt.datetime());
    res.end();
}).listen(3000); 
Posted in NodeJs

You can also read...

Leave a Reply

Your email address will not be published. Required fields are marked *