Creating Custom Modules
Now that you understand the basics of modules, it's time to create your own! Custom modules are the building blocks of any well-organized Node.js application. They help you keep your code DRY (Don't Repeat Yourself) and maintainable.
What Makes a Good Module?
- Single Responsibility: A module should do one thing well.
- Reusable: Can be used in different parts of your app.
- Testable: Easy to write tests for.
- Encapsulated: Hides internal details, exposes only what's needed.
Think of a module like a kitchen appliance. A blender only blends – it doesn't toast bread. And you don't need to know how the motor works to use it.
Example 1: A Simple Utility Module
string-utils.js
<!-- Module with multiple utility functions -->const capitalize = (str) => { if (!str) return ''; return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();};
const reverse = (str) => { return str.split('').reverse().join('');};
const countWords = (str) => { return str.trim().split(/s+/).length;};
<!-- Export all functions as an object -->module.exports = { capitalize, reverse, countWords};app.js
const stringUtils = require('./string-utils');
console.log(stringUtils.capitalize('hello WORLD')); <!-- Hello world -->console.log(stringUtils.reverse('Node.js')); <!-- sj.edoN -->console.log(stringUtils.countWords('This is a test')); <!-- 4 -->Example 2: A Module with Private Functions
Not everything needs to be exposed. You can have private functions inside a module.
user-validator.js
<!-- Private helper functions (not exported) -->const isEmailFormat = (email) => { return email.includes('@') && email.includes('.');};
const isStrongPassword = (password) => { return password.length >= 8;};
<!-- Public API -->const validateUser = (user) => { const errors = []; if (!user.name || user.name.trim() === '') { errors.push('Name is required'); } if (!isEmailFormat(user.email)) { errors.push('Invalid email format'); } if (!isStrongPassword(user.password)) { errors.push('Password must be at least 8 characters'); } return { isValid: errors.length === 0, errors };};
module.exports = { validateUser };Example 3: Module with a Class
logger.js
class Logger { constructor(name) { this.name = name; } info(message) { console.log(`[${this.name}] INFO: ${message}`); } error(message) { console.error(`[${this.name}] ERROR: ${message}`); } warn(message) { console.warn(`[${this.name}] WARN: ${message}`); }}
module.exports = Logger;app.js
const Logger = require('./logger');
const logger = new Logger('App');logger.info('Application started');Folder Structure for Modules
As your project grows, organize modules in folders:
project/├── node_modules/├── src/│ ├── utils/│ │ ├── string-utils.js│ │ └── math-utils.js│ ├── models/│ │ └── user.js│ ├── services/│ │ └── auth-service.js│ └── app.js├── package.json└── package-lock.jsonTwo Minute Drill
- Create custom modules to organize and reuse code.
- Keep modules focused on a single responsibility.
- Use `module.exports` to expose the public API.
- Keep helper functions private (not exported).
- Organize modules in a logical folder structure.
Need more clarification?
Drop us an email at career@quipoinfotech.com
