FOLASAYO SAMUEL OLAYEMI
SV_D_CURIOUS_SOFTWARE_ENGINEER'S BLOG

Follow

SV_D_CURIOUS_SOFTWARE_ENGINEER'S BLOG

Follow

How to use modules in Node.js

FOLASAYO SAMUEL OLAYEMI's photo
FOLASAYO SAMUEL OLAYEMI
·Mar 26, 2022·

2 min read

Play this article

Table of contents

  • What is a Module in Node.js?
  • How to include modules.

What is a Module in Node.js?

A set of functions you want to include in your application. Consider modules to be the same as JavaScript libraries.

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

How to include modules.

This can be done by using the require() function with the name of the module

Code Sample:

var http = require('http');

The code above give your application access to the HTTP module, and is able to create a server.

Code Sample:

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('Hello World!');
}).listen(8080);

Note: You can also create your own modules, and easily include them in your applications.

Let give an example by creating 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.

Now, save the code above in a file called "myfirstmodule.js".

You can now include and use the module in any of your Node.js files.

Code Sample:

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

You will notice that we use the module "myfirstmodule" in a Node.js file, and we also use ./ to locate the module, this means that the module is located in the same folder as the Node.js file.

You can now save the code above in a file called "demo_module.js" or any name of your choice, and initiate the file.

Thanks for reading...

Happy Coding!

Did you find this article valuable?

Support FOLASAYO SAMUEL OLAYEMI by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this