INTRODUCTION
:
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.
Ø There are
three types of modules :
·
·
Core Modules
·
local Modules
· Third-party Module
·
- 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.
v Core Module Syntax Http :
const http = require('http');
v Examples :
£ Core Module
Syntax Http :
const
http = require('http');
const
server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'tet/plain'});
res.end('Hello, Node.js!');
});
const
PORT = 3000;
server.listen(PORT,
() => {
console.log(Server running at
http://localhost:${PORT}/);
});
£ Core Module
Syntax assert :
const
assert = require('assert');
function
add(a, b) {
return a + b;
}
assert.strictEqual(add(2,3),
5, 'Expected sum of 2 and 3 to be 5');
console.log('All
tests passed successfully!');
£ Core Module
Syntax fs :
const
fs = require('fs');
const
filepath = 'example.txt';
fs.readFile(filepath, 'utf-8',
(err, data) => {
if (err) {
console.error(Error reading file:
$(err.message});
return;
}
console.log(File content: ${data});
});
£ Core Module
Syntax os :
const os = require('os');
var totalMemory = os.totalmem();
var freeMemory = os.freemem();
console.log(Total Memory :
${totalMemory});
console.log(Free Memory :
${freeMemory});
£ Core Module
Syntax :
const querystring =
require('querystring');
const queryString =
'name=John&age=30&city=NewYork';
const parsedQuery = querystring.parse(queryString);
console.log('Parsed Query:',
parsedQuery);
const objectToQueryString = { name:
'Alice', age: 25, city: 'London' };
const stringifyResult =
querystring.stringify(objectToQueryString);
console.log('Stringified Query:', stringifyResult);
- · Local Modules :
These are modules created by developers within their own projects. You create local modules by separating code into separate files and then exporting functions, objects, or variables using ‘module.exports’ or ‘exports’.
- · Third-party Modules :
These are modules created by third-party developers and made available through npm (Node Package Manager). You can install them using npm or yarn and then import them into your project using ‘require’.Some of the popular third- party modules are Mongoose, express, angular, and React.
v Examples :
§ npm install express
§ npm install mongoose
§ npm install -g @angular/cli
-Code With VDK