Node.js Modules - GeeksforGeeks (2024)

Last Updated : 31 May, 2024

Summarize

Comments

Improve

In Node.js, Modules are the blocks of encapsulated code that communicate with an external application on the basis of their related functionality. Modules can be a single file or a collection of multiple files/folders. The reason programmers are heavily reliant on modules is because of their reusability as well as the ability to break down a complex piece of code into manageable chunks.

We will discuss the different types of Node.js Modules:

Table of Content

  • Core Modules
  • Local Modules
  • Third-party modules

Core Modules

Node.js has many built-in modules that are part of the platform and come with Node.js installation. These modules can be loaded into the program by using the required function.

Syntax:

const module = require('module_name');

The require() function will return a JavaScript type depending on what the particular module returns. The following example demonstrates how to use the Node.js http module to create a web server.

JavaScript
const http = require('http');http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('Welcome to this page!'); res.end();}).listen(3000);

In the above example, the require() function returns an object because the Http module returns its functionality as an object. The function http.createServer() method will be executed when someone tries to access the computer on port 3000. The res.writeHead() method is the status code where 200 means it is OK, while the second argument is an object containing the response headers. The following list contains some of the important core modules in Node.js:

Core ModulesDescription
httpcreates an HTTP server in Node.js.
assertset of assertion functions useful for testing.
fsused to handle file system.
pathincludes methods to deal with file paths.
processprovides information and control about the current Node.js process.
osprovides information about the operating system.
querystringutility used for parsing and formatting URL query strings.
urlmodule provides utilities for URL resolution and parsing.

Local Modules

Unlike built-in and external modules, local modules are created locally in your Node.js application. Let’s create a simple calculating module that calculates various operations. Create a calc.js file that has the following code:

JavaScript
// Filename: calc.jsexports.add = function (x, y) { return x + y;};exports.sub = function (x, y) { return x - y;};exports.mult = function (x, y) { return x * y;};exports.div = function (x, y) { return x / y;};

Since this file provides attributes to the outer world via exports, another file can use its exported functionality using the require() function.

javascript
// Filename: index.jsconst calculator = require('./calc');let x = 50, y = 10;console.log("Addition of 50 and 10 is " + calculator.add(x, y));console.log("Subtraction of 50 and 10 is " + calculator.sub(x, y));console.log("Multiplication of 50 and 10 is " + calculator.mult(x, y));console.log("Division of 50 and 10 is " + calculator.div(x, y));

Step to run this program: Run the index.js file using the following command:

node index.js

Output:

Addition of 50 and 10 is 60Subtraction of 50 and 10 is 40Multiplication of 50 and 10 is 500Division of 50 and 10 is 5

Note: This module also hides functionality that is not needed outside of the module.

Third-party modules

Third-party modules are modules that are available online using the Node Package Manager(NPM). These modules can be installed in the project folder or globally. Some of the popular third-party modules are Mongoose, express, angular, and React.

Example:

  • npm install express
  • npm install mongoose
  • npm install -g @angular/cli

Example: Installing and Using Express

npm install express

Create a Simple Express Server:

JavaScript
const express = require('express');const app = express();const port = 3000;app.get('/', (req, res) => { res.send('Hello World!');});app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`);});

Run the Server:

node server.js

When you navigate to http://localhost:3000 in your browser, you should see Hello World!.



Please Login to comment...

Node.js Modules - GeeksforGeeks (2024)
Top Articles
Ask ISO
20+ of the Best Company Information Sources | AskBrian
Ups Customer Center Locations
Section 4Rs Dodger Stadium
Chase Bank Operating Hours
Davante Adams Wikipedia
OSRS Fishing Training Guide: Quick Methods To Reach Level 99 - Rune Fanatics
A Complete Guide To Major Scales
Pj Ferry Schedule
Midway Antique Mall Consignor Access
Craigslist Estate Sales Tucson
Blue Ridge Now Mugshots Hendersonville Nc
Cooktopcove Com
Chris Hipkins Fue Juramentado Como El Nuevo Primer Ministro De...
180 Best Persuasive Essay Topics Ideas For Students in 2024
104 Whiley Road Lancaster Ohio
Kitty Piggy Ssbbw
Nail Salon Goodman Plaza
Marine Forecast Sandy Hook To Manasquan Inlet
Village
Red Cedar Farms Goldendoodle
Thick Ebony Trans
Bn9 Weather Radar
Airline Reception Meaning
Amelia Chase Bank Murder
Uncovering the Enigmatic Trish Stratus: From Net Worth to Personal Life
Stouffville Tribune (Stouffville, ON), March 27, 1947, p. 1
Why Are The French So Google Feud Answers
Mkvcinemas Movies Free Download
The Pretty Kitty Tanglewood
Giantess Feet Deviantart
How to Watch the X Trilogy Starring Mia Goth in Chronological Order
THE 10 BEST Yoga Retreats in Konstanz for September 2024
Crystal Mcbooty
2008 Chevrolet Corvette for sale - Houston, TX - craigslist
Publictributes
Ferguson Employee Pipeline
20 bank M&A deals with the largest target asset volume in 2023
Panorama Charter Portal
Gfs Ordering Online
Wal-Mart 140 Supercenter Products
2007 Jaguar XK Low Miles for sale - Palm Desert, CA - craigslist
Pokemon Reborn Gyms
Executive Lounge - Alle Informationen zu der Lounge | reisetopia Basics
Unveiling Gali_gool Leaks: Discoveries And Insights
Comanche Or Crow Crossword Clue
Pas Bcbs Prefix
Best brow shaping and sculpting specialists near me in Toronto | Fresha
Rise Meadville Reviews
login.microsoftonline.com Reviews | scam or legit check
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated:

Views: 5850

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.