Introduction of Node.js Modules

Websolutionstuff | Sep-10-2021 | Categories : Node.js

In this tutorial I will give you information about Introduction of Node.js Modules. Node.js modules provide a way to re-use code in your Node.js application. Node.js modules to be the same as JavaScript libraries.

Node.js provide set of built-in modules which you can use without any further installation. like assert, crypto, fs, http, https, path, url etc...

Please check more details or modules on Built-in Module in Node js.

Include Module in Node.js

for include 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('Websolutionstuff !!');
}).listen(3000);

 

Create Custom Modules

You can create your custom modules and you can easily include in your applications.

In below example creates a module that returns a date and time object.

exports.custom_DateTime = 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 "custom_module.js".

 

 

Include Custom Modules

Now you can include and use the module in any of your Node.js files.

var http = require('http');
var dt = require('./custom_module');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("Date and Time : " + dt.custom_DateTime());
  res.end();
}).listen(3000);

Notice that the module is located in the same folder as the Node.js file. or add path of module file.

Save above code in "custom_module_demo.js" file. and run below command in your terminal.

node custom_module_demo.js

Output :

Date and Time : Wed Sep 08 2021 20:05:04

 


You might also like :

Recommended Post
Featured Post
Laravel 10 Composer-runtime-api ^2.2 Error - Fixed
Laravel 10 Composer-runtime-ap...

In this article, we will see laravel/framework[v10.0.0, ..., v10.0.3] require composer-runtime-api ^2.2 error fixed...

Read More

Mar-07-2023

How To Show Loading Spinner In Ajax jQuery
How To Show Loading Spinner In...

In this article, we will see how to show loading spinner in ajax jquery. Using ajaxStart() and ajaxStop() method we...

Read More

Jul-06-2022

How To Send Email With Attachment In Laravel 8
How To Send Email With Attachm...

In this tutorial i will show you how to send email with attachment in laravel 8. As we all know mail functionalities are...

Read More

May-05-2021

How To Use CSS In React JS
How To Use CSS In React JS

In this article, we will see how to use CSS in React JS. Also, we will see camel case CSS in React JS. React i...

Read More

Aug-17-2022