Skip to content
Home » Modules In NodeJs | Node.Js Tutorial #2

Modules In NodeJs | Node.Js Tutorial #2

Modules In NodeJs | Node.Js Tutorial #2

Hey Programmers, In the Previous Tutorial We Installed Node.js And Created Our First Hello World Program Using NodeJS And In this Post We will be Learning About Modules In NodeJs And Working With Few Modules In NodeJS  Like HTTP, File System, URL etc. 

Table Of Contents:

  • Modules In NodeJS
  • NodeJS Built-In Modules
  • List of NodeJs Built-In Modules
  • Including Modules
  • Creating Your Own Moule In NodeJS
  • Include Your Own Module In Any Program
  • HTTP Module In NodeJs
  • Creating a Basic Web Server In NodeJS
  • File System Module In NodeJS
  • URL Module In NodeJS

Modules In NodeJS

Modules are like JavaScript Libraries as We Work With Libraries, Modules Are Also Same But We Just Use Modules In NodeJS By Installing It With the Help of NPM (Node Package Manager). 

NodeJS Built-In Modules

NodeJS has some Set of Built-In Modules Which Can Be Used Without Installing It. We Just Have To Import It In Any Program to Use It. 

List of NodeJs Built-In Modules

assertProvides a set of assertion tests
bufferTo handle binary data
child_processTo run a child process
clusterTo split a single Node process into multiple processes
cryptoTo handle OpenSSL cryptographic functions
dgramProvides implementation of UDP datagram sockets
dnsTo do DNS lookups and name resolution functions
domainDeprecated. To handle unhandled errors
eventsTo handle events
fsTo handle the file system
httpTo make Node.js act as an HTTP server
httpsTo make Node.js act as an HTTPS server.
netTo create servers and clients
osProvides information about the operation system
pathTo handle file paths
punycodeDeprecated. A character encoding scheme
querystringTo handle URL query strings
readlineTo handle readable streams one line at the time
streamTo handle streaming data
string_decoderTo decode buffer objects into strings
timersTo execute a function after a given number of milliseconds
tlsTo implement TLS and SSL protocols
ttyProvides classes used by a text terminal
urlTo parse URL strings
utilTo access utility functions
v8To access information about V8 (the JavaScript engine)
vmTo compile JavaScript code in a virtual machine
zlibTo compress or decompress files

Including Modules

In Order to Include a Module In a Program. Use require() Function With the Name of the Module:

var http = require('http');

Creating Your Own Moule In NodeJS

As NodeJS Allows us to Work With Other Modules Unlike Of This We can Also Create Our Own Modules In NodeJS And Import It In Other Programs.

Creating a Date Time Module Using the JavaScript Date() Function:

exports.DateTime = function () {
  return Date();
};

Save the File With the filename Module.js

Include Your Own Module In Any Program

var http = require('http');
var DateTime = require('./Module');
http.createServer(function (req, res){
  res.write('Hello World!');
  res.end();
}).listen(3000);

HTTP Module In NodeJs

In Node.js, There is a Bult-In Module Called HTTP (Hyper Text Transfer Protocol) Which Allows Us to Listen to Server Ports & Give the Responce Back to the Client.

To Include the HTTP Module Use the require() Function:

var http = require('http');

Creating a Basic Web Server In NodeJS

const http = require('http')
const port = 3000
const server = http.createServer(function(req ,res){
    res.write('Web Server In Node.js')
    res.end()
})
server.listen(port, function(error) {
    if (error) {
        console.log('Something Went Wrong', error)
    }
    else{
        console.log('Sever Started Sucessfully', + port)
    }
})

File System Module In NodeJS

NodeJS has a Module Called File System which allows Us to Work With Our File System Present In Our Computer.

var fs = require('fs');

Common uses for the File System module:

  • Read files
  • Create files
  • Update files
  • Delete files
  • Rename files

Reading Files Using NodeJS

We can Read Files In NodeJS By Using the fs.readFile() FunctionSuppose We Have a File Called index.html In Which We Have the Following Content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Node.js File System</title>
</head>
<body>
    <h2>Your Are Viewing Through Node.js</h2>
</body>
</html>

Now Create a New File Named Read.js And Copy the Following Code:

var http = require('http');
var file_system = require("fs");

http.createServer(function(req, res){
    fs.readFile('index.html', function(err, data){
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        return  res.end();
    });
}).listen(3000);

Now It Will Read the Index.html File And Give Us the Desired Output.

URL Module In NodeJS

The URL module splits up a web address into readable parts. URL Module Uses the require() method.

var url = requie('url');

Parse an Address Using the url.parse() Function, It Will Return the URL Object With Each Part of the Address as a Property:

var url = require(url);

var adr = 'http://localhost:3000/';
var q = url.parse(adr, true);

console.log(q.host);
console.log(q.pathname);
console.log(q.search);

var qdata = q.query;
console.log(qdata.month);

So This Was It For this Blog, See you In the Next One Till Then Keep Coding Keep Exploring!

Previous NodeJS Tutorials:

Getting Started NodeJS + Writing Hello World! | Node.Js Tutorial #1

1 thought on “Modules In NodeJs | Node.Js Tutorial #2”

  1. Pingback: What is Node Package Manager? | Node.Js Tutorial #3 - Mr Programmer

Leave a Reply

Your email address will not be published. Required fields are marked *

You cannot copy content of this page

Top 10 Programming Languages to Learn In 2023! 9 Best Extensions For Web Developers! | Chrome Extensions For Web Developers Web Development Roadmap Best Resources to Learn PYTHON FREE! Web Vs App Development- Which one is Better?