Node.js Modules

What is a Module in Node.js?

A module in Node.js is a reusable block of code that can be imported and used in other files. It helps in organizing and structuring applications.

A Node.js module is a reusable piece of code that can be imported and used in other files.


Types of Modules:

  • Built-in Modules - Provided by Node.js (e.g., fs, http, path).
  • User-defined Modules - Created manually using .js files.
  • Third-party Modules - Installed via npm (e.g., express, lodash).

Creating a Module:

  • Use module.exports to export functions/variables.
  • Use require() to import a module.

Example:

math.js

module.exports.add = (a, b) => a + b; 

app.js

const math = require('./math');
console.log(math.add(2, 3)); 

Modules help in organizing and reusing code efficiently


Conclusion

Node.js modules simplify code organization, promote reusability, and enhance maintainability. They allow developers to separate concerns, making applications more modular and scalable. Whether using built-in, custom, or third-party modules, they help streamline development and improve efficiency.

Previous Next