0
0
NodejsHow-ToBeginner · 3 min read

How to Create Custom Module in Node.js: Simple Guide

To create a custom module in Node.js, write your code in a separate file and export the parts you want to share using module.exports. Then, import it in another file using require() to use the exported functions or variables.
📐

Syntax

In Node.js, a custom module is created by exporting values from a file using module.exports. You can export a function, object, or any value. To use the module, import it with require().

  • module.exports: Defines what the module shares.
  • require(): Loads the module in another file.
javascript
/* myModule.js */
module.exports = {
  greet: function(name) {
    return `Hello, ${name}!`;
  }
};

/* app.js */
const myModule = require('./myModule');
console.log(myModule.greet('Alice'));
💻

Example

This example shows a custom module that exports a greeting function. The main file imports it and calls the function to print a message.

javascript
/* greetModule.js */
function greet(name) {
  return `Hello, ${name}! Welcome to Node.js modules.`;
}

module.exports = greet;

/* index.js */
const greet = require('./greetModule');

console.log(greet('Bob'));
Output
Hello, Bob! Welcome to Node.js modules.
⚠️

Common Pitfalls

Common mistakes include forgetting to export the function or object, using incorrect file paths in require(), or mixing exports and module.exports incorrectly.

Always use module.exports to export a single item or an object. Using exports alone can cause unexpected results if reassigned.

javascript
/* Wrong way: reassigning exports (does not work as expected) */
exports = function() {
  console.log('This will not be exported correctly');
};

/* Right way: use module.exports */
module.exports = function() {
  console.log('This works correctly');
};
📊

Quick Reference

Remember these key points when creating custom modules:

  • Use module.exports to export your module's API.
  • Use relative paths with require() to import your module.
  • Export functions, objects, or values as needed.
  • Keep module files focused on a single responsibility.

Key Takeaways

Use module.exports to share code from your custom module.
Import your module with require() using the correct relative path.
Avoid reassigning exports; always use module.exports for clarity.
Keep your module focused and export only what is needed.
Test your module by importing and calling its exported parts.