Nodejs modules are fundamentals concepts in the Node.js that enable you to organize and re-use code.
- It's allowed you to break the code into smaller and manageable pieces.
- Making easier to maintain and collaborate.
- Modules helps you to encapsulate the code, so you can import and use it on other parts of your application.
- Without creating a global variable or causing naming conflicts
it's very fundamental mostly used to create a clean structure of our projects.
we are using this CommonJS Modules lot in our Nodejs Projects
like creating a serviceEg, We can write a separate file for getting current currency conversion rates, get dates, day and mostly often for the configs, constants we can use these modules to store site configs constants etc...
*like for the constants *
LANG="en"
CURRENCY="usd"
BASEURL="yourbaseurl.com"
CommonJS Modules
Nodejs uses CommonJS module system, which defines a way to create, import and export modules.
CommonJS modules have two important main components.
You can export functions, variables or objects using modules.exports or exports object.
//Space.js
module.exports = {
rocketFunction: function () {
return "Rocket launched!";
},
Moon: 1
};
Importing Modules
You can import the exported content from another module using require function.
Const spaceFun = require(โspace.jsโ)
spaceFun.rocketFunction()
spaceFun.moon
Output
Rocket launched!
1
Another Example
Get export multiple modules.
// userInfo.js
// A function that greets the user with a personalized message
function greetUser(name) {
return `Hello, ${name}! Welcome to my module.`;
}
// An object containing some module information
const moduleInfo = {
moduleName: "My Node.js Module",
author: "John Doe",
description: "This is a simple Node.js module example.",
version: "1.0.0"
};
// Exporting the greetUser function and moduleInfo object
module.exports = {
greetUser,
moduleInfo
};
Importing Modules
const userInfo = require('./info.js');
console.log(userInfo.greetUser("John"));
// Output: "Hello, John! Welcome."
console.log(userInfo.moduleInfo);
// Output: Object with module information
console.log(userInfo.moduleInfo.author);
// Output: Get author value in module information Object it will outputs "John Doe"
Make use of, Another example
//shuffleArray.js
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
module.exports = {
shuffleArray,
};
Importing Module
const shuffleArray = require("./shuffleArray");
const colors = ["red", "green", "blue", "yellow", "purple"];
console.log("shuffleArray ", shuffleArray.mixArray(colors));
Output(may):
["green", "red", "blue", "purple", "yellow"]
So, That's were you can import the modules
Stay tuned for more advanced articles where we'll explore the depths of Node.js
If you have any queries or just want to share your Node.js anecdotes, and command below
happy coding! ๐
Top comments (0)