Modules are similar to javascript libraries. A set of functions used inside an application.

  • To include or to use a module, require() is used inside an application
  • We can create our own Modules. And can be used inside an application using require()
  • To use http module
var http_module = require('http');
http_module.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('Hello World!');
→ With the above code, we can create a http server listening to port 8080. Using HTTP Module
Let’s create server.js with above code. And run this code using “node server.js”
  1. Create a file named server.js
  2. Copy & Paste the code and save it.
  3. Run the application using command “node server.js”
  4. Now open a browser and try this link “http://localhost:8080
    1. You will get the hello world as a response

server js

Below screenshot shows running server.js application.

running server-js

Below screenshot shows outcome of the program.

hello world

Our own Modules:

exports.my_Date_Time = function () {
  return Date();

→ Above code used to create our own module. It returns the date. We use export keyword to make the methods available outside the module. Let’s assume above piece of code saved under “my_Date_Time.js”
→ Module my_Date_Time can be access by other application as below by using require()

var http_module = require('http');
var dtnow = require('./my_Date_Time’);

http_module.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("Current date is : " + dtnow.my_Date_Time());

our own modules

Below screenshot shows outcome of the program:

output current date

Build in Modules:

Nodejs has many built-in modules. Below are most frequently used modules.

  1. HTTP – to transfer data over http. Using this module, node js can be used to create a HTTP Server and it can listen to a specific port. From where it can receive and respond to requests from http client. We have seen this in our previous example.
  2. FS – File system, used to access the files. This module is used to Read, Write, Create, Delete, Update files.
    1. fs.readFile() – to read a file
    2. -> to create a file
    3. fs.appendFile() -> to Create / Update a file
    4. fs.writeFile()-> to Create / Update a file
    5. fs.unlink() -> to delete a file
    6. fs.rename() -> to rename a file
Below code shows how to use above functions in a node js application.
Subscribe Now