What is Node.js Modules ?
Node.js Modules is a set of functions which you can include in your application. Node.js Modules is same as JavaScript libraries.
Node.js provides many built-in modules like http, express fs, path, events, string, moments, events, os , url etc.
We can include all Node.js module in our applicaton using require() function.
How to access Node.js module?
Write below code in app.js . You can access module using require() function as below.
const http = require('http');
const port = 5555;
const server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Welcome to aryatechno tutorials!');
}).listen(8080);
server.listen(port function() {
console.log(`Server running at port ${port}: http://127.0.0.1:${port}`)
})
Run above code using cmd : node app.js
How to create our own modules?
We can create our own modules using exports keyword as below.
exports.moduleName = async function (req, res, next) {
return data;
}
Use the exports keyword to make properties and methods available outside the module file.
Example,
Create calculation.js file
exports.add = function (a, b) {
return a + b;
};
exports.subtract = function (a, b) {
return a - b;
};
create app.js file.
var http = require('http');
const math = require('./calculation');
const server = http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write("<br>Addition:"+math.add(5,4));
res.end('<br>Hello, This is a Node.js server!\n');
});
console.log("Addition:", math.add(5, 3));
console.log("Subtraction:", math.subtract(5, 3));
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Run server node app.js
Output will be as below.
Addition: 8
Subtraction: 2
Server running on http://localhost:3000
Comments