Node.js Modules
Last updated onNode.js modules are like small building blocks that come together when you use tools to construct the entire structure. This means that when you build your application using Node.js, the modules help you assemble your project quickly.
In the tutorial, you will understand what modules are, their definition, and types, and how to include them in your project.
So, let’s get started with the main definition.
Definition and Types of Node.js Modules
Node.js Modules are nothing but files or groups of files in which you write some amount code to do a particular thing which can be exported and then imported elsewhere.
A module has a scope, and the code within it is isolated from other parts of your application unless you explicitly expose it by exporting a specific part.
So, using modules in Node.js helps you to do the following on your project:
- Keep your code organized.
- Make your code reusable.
- Avoid any conflicts.
- Easier testing.
- Use existing tools.
Basically, Node.js has 3 types of modules which are like the below list:-
- Core Modules
- Local Modules
- Third-Party Modules (NPM Modules)
So let’s take a look at each one in detail.
Core Modules
These are already built-in Node.js which comes with Node.js installation. These modules give us essential functionalities that are already written in C++ or JavaScript.
Additionally, these modules are built to optimize the performance used in handling file systems, managing HTTP requests, and more else.
They are like fs
, http
, path
, crypto
, and events
.
Here is an example that shows you how to work with file stream in Node.js.
var fs = require('fs');
// Reading a file asynchronously
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});
Core modules are loaded automatically by Node.js when requested and can be accessed using the require()
function followed by the name of the module.
here is another example with an HTTP request.
// Using the built-in 'http' module to create a simple HTTP server
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
Now, let’s go to the below section to understand what local modules are.
Local Modules of Node js
Local modules are all files that you create on your Node.js project. For example, if your application does some stuff such as connecting to a database or processing, you are creating that and using export/import to use it inside your application.
So in the following example, I created two files and printed the file name in the terminal console as an output. The first file is dbconnection.js
and the name of the second one is server.js.
// dbconnection.js
var connected = () => console.log("database is connected!");
module.exports = { connected }
In this case, the connected()
function is a local module inside your local project and you can use it anywhere. let’s import it inside server.js
file.
// server.js
var {connected}= require("./dbconnection");
connected();
That will show you the console.log
result in your terminal.
Anyway, in the following section, you will learn how to use the third-party modules. Let’s move on.
Third-party modules (NPM Modules)
These modules were already created by other developers and shared in the community of JavaScript. This community is called NPM which means the Node Package Manager.
When you use these packages, you will save development time. They can be downloaded using simple commands.
let’s see an example:
// Import the Express module
const express = require('express');
// Create an Express application
const app = express();
// Define a route for the home page
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// Start the server on port 3000
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Anyway, let’s move into the following section to understand how to load and require modules in Node.js.
Loading and Requiring Modules
As we said before, Node.js modules are functions that help us to build our project. And we can’t use it until invoke it inside the target file. So the process of using these modules in your application involves loading and requiring them to use the require()
function.
The require() Function
This function is used to load and bring a module into the current file when you just call it through this function require(<file_path_or_built_in>)
.
Here is an example:
// Loading a built-in module
const fs = require('fs');
// Loading a local module
const myModule = require('./myModule');
// Loading a third-party module
const express = require('express');
Module Caching and the Role of module.exports
When a module is loaded for the first time, Node.js stores it in an internal cache. The next time you require the same module, Node.js retrieves it from the cache instead of loading it from the file system again.
Let’s see an example:
// First time requiring the module
const myModule = require('./myModule');
// Requiring the same module again
const myModuleAgain = require('./myModule');
// Both variables point to the same cached module
console.log(myModule === myModuleAgain); // true
Additionally, module.exports
is an object that a module returns when it is required in another file. By default, an empty object ({}
) which is assigned to module.exports
, but you can customize what is exported from the module by assigning different values to it.
Let’s see an example:
// Exporting a function
function greet(name) {
return `Hello, ${name}!`;
}
// Assign the function to module.exports
module.exports = greet;
That’s all, let’s summarize it.
Wrapping Up
The article presents a classification of Node.js modules, which are important elements in building Node.js applications. It explains that the composition of modules can be a file or a combination of several files with functionality and they can be exported or imported out of the application. This in turn makes it easier to test the application since such common problems are alleviated when modularization is used to structure the code.
This tutorial presents a useful categorization into three types of Node.js modules: Core Modules:
- Core Modules: are modules that form part of the Node.js framework and essentially carry the generic functions such as file operations (file system – fs), performing HTTP (HTTP), and many more code snippets and illustrations are also shown on these modules.
- Local Modules: These are the created modules designed by the developers to be used in their Node.js application. The article explains how to create a local module, export it, and use it in another module with the help of appropriate samples.
- Third-party packages (Npm modules) These are the break pack developed by the javascript society and are distributed through the npm.
Thank you for reading. Happy Coding!