Node.js Modules
What is Modules in Node.js
Modules are parts of code that can be utilized in several instances and shared between documents or tasks in Node.js.
They facilitate the grouping of code, make it reusable and maintainable. With CommonJS module system, JavaScript application can be split into modules located in separate files.
Creating and Exporting Modules:
In order to come up with a module in node.js, one usually defines their functions/classes/variables within a file then exports them for use by other files.
Example of a module file named math.js:
// math.js
const add = (a, b) => {
return a + b;
};
const subtract = (a, b) => {
return a - b;
};
// Exporting functions
module.exports = {
add,
subtract
};
Here we have math.js where two functions add and subtract have been defined followed by exporting them via module.exports.
Loading and Using Modules in Node.js Applications:
Once you create a module then export it from such file it is possible to load this into another file using require() function.
Example of a Node.js application file app.js using the math.js module:
// app.js
const { add, subtract } = require('./math');
console.log(add(5, 3)); // Output: 8
console.log(subtract(10, 4)); // Output: 6
In the app.js file we call require(‘./math’) which loads the math.js module. Afterwards its contents (functions add and subtract) will be available to the rest of our program.
Core Modules vs. Local Modules:
Node has core modules like http, fs, path which are prebuilt hence no need to install them. One can use them directly without installing through npm.
Node.js provides core modules such as http, fs, and path that are built-in and don't require installation. You can use them directly in your code without needing to install them via npm.