How to use modules in Node.js

Introduces how to modify response information in Node.js. The code is also posted on Git Hub, so please refer to it.

overview

Node.js takes a modular approach that allows developers to group related functionality together and express code in a way that is easy to reuse and manage. A Node.js module is a JavaScript file, and functions and objects defined within that file are by default only available within that module.

Here, we will explain the routing method using the following versions.

nodejs v19.7.0

In addition, all the code created this time is posted on GitHub.

Types of Node.js modules

Node.js modules fall into three main categories:

  1. Core Modules: Modules built into Node.js. These modules form part of the Node.js API and can be loaded at any time using the require() function. For example, http, url, path, fs, etc.

  2. Local modules: Self-defined modules created by users. These modules are only used within a specific application.

  3. Third Party Modules: Modules created by other developers that are installed via npm (Node Package Manager). These can be loaded using the require() function.

How to use core modules

Core modules are built into Node.js and can be loaded at any time using the require() function. For example, to create an HTTP server using the http module:

core.js

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  console.log('Server is running on port 3000');
  res.end();
}).listen(3000);

Commentary

  • Import HTTP module
var http = require('http');

‘http’ is a Node.js built-in module that provides functionality for HTTP communication. Here we import (load) the ‘http’ module and assign it to the variable http.

  • Create HTTP server
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  console.log('Server is running on port 3000');
  res.end();
}).listen(3000);

Create an HTTP server using the createServer method of the ‘http’ module. This method is passed a callback function that takes the request and response as parameters. This callback function will be executed each time the server receives a request.

Start the server on port 3000 using the listen method of the created HTTP server. The server will now listen for client requests on port 3000.

test

curl -X GET http://localhost:3000

This code imports the http module and uses the http.createServer() function to create an HTTP server. The createServer() function takes a callback function that will be executed when an HTTP request is received. This callback function takes two arguments, req and res. req is the HTTP request object and res is the HTTP response object. The res.writeHead() function sets the response headers. The res.end() function sets the response body. The listen() function starts the server on the specified port.

How to use local modules

A local module is a self-defined module created by the user. To create a local module, follow these steps:

localmodule.js

// create module
exports.myDateTime = function () {
  return Date();
};

local.js

// module import
var http = require("http");
var dt = require('./localmodule');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("Current date is: " + dt.myDateTime());
  res.end();
}).listen(3000);

Commentary

  • importing local modules
var dt = require('./localmodule');

‘./localmodule’ points to the module you created yourself. Here we are importing (loading) the ’localmodule’ module and assigning its exported functions and objects to a variable called dt. This module assumes that you have exported a function called myDateTime.

  • Create HTTP server
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("Current date is: " + dt.myDateTime());
  res.end();
})

Create an HTTP server using the createServer method of the ‘http’ module. This method is passed a callback function that takes the request and response as parameters. This callback function will be executed each time the server receives a request.

  • Setting response headers
res.writeHead(200, {'Content-Type': 'text/html'});

Within the callback function, set the HTTP response status code and headers using the writeHead method of the response object res. Here the status code is set to 200 (OK: the request was processed successfully) and the ‘Content-Type’ header is set to ’text/html’.

  • display current date
res.write("Current date is: " + dt.myDateTime());

Use the write method of the response object res to display the current date. Here, we call the dt module’s myDateTime function to get the current date and send that date as a response to the client.

  • end of response
res.end();

End the response with the end method of the response object res. This method tells the client that the response headers and body have all been sent and the communication is complete.

  • Start server
}).listen(3000);

Start the server on port 3000 using the listen method of the created HTTP server. The server will now listen for client requests on port 3000.

test

curl -X GET http://localhost:3000

How to use third party modules

Third-party modules are modules created by other developers that are installed via npm (Node Package Manager). To install third-party modules, follow these steps: This time, we will install the express module.

npm install express

third.js

const express = require('express');

const app = express();

app.get('/', (req, res) => {
  res.send('Hello, Express.js!');
});

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

Commentary

This code uses Node.js and Express.js to build a web server and listen on port 3000. Specific functions are as follows.

  • Importing Express modules
const express = require('express');

Express is a lightweight and flexible web application framework for Node.js. This line imports the Express module and assigns it the constant express.

  • Generate Express application
const app = express();

Here we are generating an Express application by calling the express() function. This application object (app) has many methods about the server, such as routing and middleware configuration.

  • Define GET request to root route
app.get('/', (req, res) => {
  res.send('Hello, Express.js!');
});

We use the app.get() method to define the behavior when a GET request to the root path (’/’) is received. The second argument is the callback function, which takes the request (req) and response (res) objects as arguments. This callback function will send the string “Hello, Express.js!” back to the client.

  • Start server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

The app.listen() method will start the server on the specified port (3000 in this case). If you specify a callback function as the second argument, that function will be executed when the server starts. This example prints the message “Server started on port 3000” to the console when the server starts.

The final directory structure will look like this:

express-core-project
├── node_modules
│ └── (dependency package)
├── third.js
├── package-lock.json
└── package.json

test

curl -X GET http://localhost:3000

summary

I explained how to use modules in Node.js.