What is a Module in Node.js?
A module is a way of grouping related functions or data in one or more JavaScript files in Node. js. Modules can be used again in different parts of a Node. js application without affecting other modules or the global scope. Each module has its own environment, so it is isolated from other modules.
Node.js has a number of built-in modules which we can use without any further installation. Here are some of the built-in modules:
- assert
- buffer
- child_process
- crypto
- domain
- stream
- path
- os
- http
- https
You can find more modules here: https://nodejs.org/api/modules.html
How to include Modules?
To include a module in node.js file, we use the require()
function with the name of the module:
JavaScript
var http = require('http');
After including a module, we can apply it in our application. This is an example of using the http module that we imported.
JavaScript
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);