Q1. How do you create a custom module in Node.js?
Create a JavaScript file, define functions/variables, and export them. Example: math.js:
const add = (a,b) => a+b; module.exports = { add }; Then in another file: const math = require('./math'); console.log(math.add(2,3));. This helps organize code into reusable pieces.Q2. What are the best practices for creating modules?
Keep modules focused on a single responsibility. Name files clearly. Use module.exports to expose the public API. Keep private functions truly private (not exported). Document your module's usage. Consider using index.js as the entry point for folders. Handle errors gracefully within modules.
Q3. How do you create a module that exports a class?
Define the class and export it:
class User { constructor(name) { this.name = name; } greet() { ... } } module.exports = User; Then import: const User = require('./user'); const user = new User('John');. This is common for object-oriented designs.Q4. Can you have a folder as a module?
Yes, create a folder with an index.js file. When you require the folder, index.js is loaded. Example: lib/index.js exports multiple modules. Then require('./lib') imports everything. You can also set the "main" property in package.json within that folder to specify a different entry point.
Q5. How do you handle circular dependencies?
Circular dependencies happen when module A requires B and B requires A. Node.js handles this by returning an incomplete exports object from the first require. To avoid issues, restructure code to remove cycles, use dependency injection, or lazy require inside functions instead of at top level.
