Author Profile Altaf Shaikh
Altaf Shaikh

BE Engg | Python Dev | Content Writer | Founder of TeachMeBro | Blockchain Dev | Django

Node.js Modules

January 24th 2021   155

Node.js Modules
Node.js Modules

What is a Module in Node.js?

In NodeJS, every JS file is a module.

Consider modules to be the same as JavaScript libraries. A set of functions , variables, you want to include in other JS files (modules) of your application.

Built-in Modules

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

Include Modules

To include a module, use the require() function with the name of the module:

var http = require('http');

Now your application has access to 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 World!');

}).listen(3000);

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:

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(3000);

Notice that we use ./ to locate the module, that means that the module is located in the same folder as the Node.js file, if you want to go one folder up use ../

Save the code above in a file called "demo_module.js", and run the file:

node demo_module.js

If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:3000