This article will explain Node.js and its modules with examples, and we will create our own custom server using the Node.js application.
To understand and create the Node.js application, please download and install it from the official site:
node.js
Node.js
According to official documentation,
- Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine for easily building fast and scalable network applications.
- Node.js is free
- Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
- Node.js uses JavaScript on the server
- Node.js modules
Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files which can be reused throughout the Node. js application.
In short we can break large javascript files into multiple files and reuse it.
Let's create your first project in node.js application
Hello World
Step 1
Open command prompt and navigate to your project directory (My project directory is D:\Arvind\solution\nodesolution\nodeExamples).
Step 2
Type npm init and answer the following question as per the following details.
Step 3
To create a blank .js file type the below command (It will create blank index.js in our current directory).
Step 4
Open index.js file in your editor (visual studio code) and write the below code.
- console.log("Hello World")
Step 5
To run and see the ouput type node index.
Since we had completed our first project in node.js application, let's see the node modules.
Node.js Module Types
There are basically three types of modules,
- File based Modules
- Core Modules
- External or Third Party Modules
File based Modules
This types of modules are created locally in your node.js application. It includes different functionalities of your application in seperate files and folders.
The require function is used to import a module in nodes.js application.
Example
Create LocalModule.js file and insert the follwing code.
-
-
- const calc = {
-
- add: function (num1, num2) {
- return num1 + num2
- },
-
- subtract: function (num1, num2) {
- return num1 - num2;
- },
-
- multiply: function (num1, num2) {
- return num1 * num2;
- },
-
- divide: function (num1, num2) {
- return num1 / num2
- }
- };
-
-
- module.exports.calc = calc;
To use the above functionality in a different module, create index.js and write the code
-
- const myCalculation = require('./LocalModule.js');
-
- const num1 = 5;
- const num2 = 4;
-
-
-
- console.log(`Addition of ${num1} and ${num2} is: ${myCalculation.calc.add(num1, num2)}`);
- console.log(`Subtraction of ${num1} and ${num2} is: ` + myCalculation.calc.subtract(num1, num2));
- console.log(`Multiply of ${num1} and ${num2} is: ` + myCalculation.calc.multiply(num1, num2));
- console.log(`Divide of ${num1} and ${num2} is: ` + myCalculation.calc.divide(num1, num2));
Now type node LocalModule to see the ouput.
Core Modules
It is also known as (built in modules).
These core modules are compiled into its binary distribution and load automatically when Node.js process starts.
In order to use Node.js core or NPM modules, you first need to import it using require() function as shown below.
- const variableName = require('module_name');
- const path = require('path');
Example
Write the below code in CoreModule.js file.
-
- const path = require('path');
-
-
- console.log("Directory of index file: " + path.dirname(__filename));
- console.log("Extension of index file: " + path.extname(__filename));
-
-
-
To see the ouput type command node CoreModule
External or Third Party Module
As the name suggests it is a third party module which needs to install in order to use in your node.js application by using NPM (Node Package Manager).
It will create node_modules folder in your node application.
Example
To demonstrate third party or external modules, I have used the third party module https://www.npmjs.com/package/dota2-heroes which contains function random() and it gives the random hero's name wherever we call random function.
To use the above library first we have to install it and then use it by importing require('dota2-heroes') in your node application.
To install the library write the below command in your terminal.
To consume the above library in your application, write below code in ThirdPartyModule.js file
-
-
-
-
- const names = require('dota2-heroes');
-
-
- const randomName = names.random();
-
-
- console.log("Heroes Name is :" + randomName);
To see the ouput type command node ThirdPartyModule
Create Custom Server using node.js
Let's create the custom server step by step.
Step 1
Open command prompt and create package.json file by using command
Step 2
Create blank index.js file by using command
Step 3
Create file customserver.js and write the below code.
-
- const httpOperation = require('http');
- const fileOps = require('fs');
- const path = require('path');
-
-
- const hostName = "localhost";
- const port = 9999;
-
-
-
-
-
-
-
-
-
- const server = httpOperation.createServer((request, response) => {
-
- if (request.method === 'GET') {
- let fileUrl;
-
- if (request.url === '/') {
- fileUrl = "/index.html";
- } else {
- fileUrl = request.url;
- }
-
- let filePath = path.resolve('./HTML' + fileUrl);
-
- const fileExt = path.extname(filePath);
-
- if (fileExt === '.html') {
- fileOps.exists(filePath, (isExists) => {
- if (isExists) {
- response.statusCode = 200;
- response.setHeader('Content-Type', 'text/html');
- fileOps.createReadStream(filePath).pipe(response);
- } else {
- showError(response, fileUrl, 'is not exist.');
- }
-
- });
- } else {
-
- showError(response, fileUrl, 'is not HTML file.');
- }
-
- } else {
-
- showError(response, fileUrl, 'is not GET Method.')
- }
-
- });
-
-
-
-
-
-
-
-
- function showError(response, fileUrl, errorMsg) {
- response.statusCode = 404;
- response.setHeader('Content-Type', 'text/html');
- response.end('<html><body><h1>Error 404 ' + fileUrl + ' ' + errorMsg + '</h1></body></html>');
- }
- server.listen(port, hostName, () => {
- console.log(`Server run at http:
- });
Step 4
Create index.html file under HTML folder and write below code.
Note
I have created simple index.html file for demonstration purpose.
- <html>
- <body>
- <h1>
- Welcome to node.js tutorial
- </h1>
- </body>
- </html>
Step 5
Write one line code in package.json file under script tag "start": "node customserver"
Step 6
To start the server type the below command:
Step 7
To see the ouput browse http://localhost:9999 which shows 'welcome to node.js tutorial' on the page.
You can download all the source code from the attachment.