English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer & URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

Other NodeJS

Node.js Modules

Node.js modules are function libraries that can be used in Node.js files.

There are three types of modules in Node.js depending on the position to be accessed. They are:

  1. Built-in Modules

    These are modules that come with Node.js installation. Refer to the list of built-in modules in Node.js.

  2. User-defined Modules

    These are modules written by users or third parties. We will learn more about user-defined modules in the 'Node.js User-defined Modules' section.

    • Creating a Node.js Module 

    • Extending Node.js Modules

  3. Third-party Modules

    There are many available modules online that can be used in Node.js. The Node.js package manager (NPM) helps to install these modules, extend them when necessary, and publish them to repositories like Github for access on distributed computers.

    • Installing Node.js Modules Using NPM

    • Extending Node.js Modules

    • Publishing Node.js Modules to Github Using NPM

Including a Module

Including a module in a Node.js file allows us to use the publicly exposed functions of the module.

Syntax

The following is the syntax for including modules in a Node.js file.

var http =require('<module_name>');

Example

To include the 'http' module in a Node.js file, we need to write the following require statement before using the http module.

var http =require('http');

Using Module Functions

After including the module by assigning it to a variable, you can access the functions in the module through the variable.

In the above module section, an example that includes the http module is provided. Now, we will use the function createServer() of the http module to demonstrate how to use module functions.

 
var http = require('http'); 
 
http.createServer(function(req, res) { 
  res.writeHead(200, {'Content-Type': 'text/plain'}); 
  res.write('Hello from Node.js!'); 
  res.end(); 
 }).listen(8080);

This function creates an HTTP server and responds with 'Hello from Node.js!' as the response. Listen to port808When 0 sends an HTTP request.

Conclusion:

In this Node.js tutorial, we have learned about Node.js modules, how to include them in Node.js files, and how to use the functions of Node.js modules.