Node.js Local Module
A local module in Node.js refers to a custom module created in an application. Unlike the built in or third-party modules, local modules are specific to the project and are used to organize and reuse your code across different parts of your application.
Local Module in Node.js
Local modules in Node.js application allow developers to structure their codebase into manageable, reusable components. By defining inter-related functions, objects, and classes within a module, you can keep your code organized and maintainable. Local modules can represent anything from utility functions to complex business logic, and they can be imported into other files using the require function.
Features
- Local modules allow you to encapsulate related code within a single file, making it easier to manage.
- Functions, objects, or classes defined in a local module can be reused across multiple files, reducing code duplication.
- Local modules promote modularity, enabling you to build applications with well-defined, independent components.
Steps to Implement Local Modules
Define a Local Module
Local module must be written in a separate JavaScript file. In the separate file, we can declare a JavaScript object with different properties and methods.
Create a local module with the filename Welcome.js
// Filename - Welcome.js
const welcome = {
sayHello: function () {
console.log("Hello GeekforGeeks user");
},
currTime: new Date().toLocaleDateString(),
companyName: "GeekforGeeks"
}
module.exports = welcome
Explanation: Here, we declared an object 'welcome' with a function sayHello and two variables currTime and companyName. We use the module.export to make the object available globally.
Import and Use Local Module
In this part, import from the file and use the above module in the app.js file.
// Filename - app.js
const local = require("./Welcome.js");
local.sayHello();
console.log(local.currTime);
console.log(local.companyName);
Explanation: Here, we import our local module 'sayHello' in a variable 'local' and consume the function and variables of the created modules.
Output:
Hello GeekforGeeks user
12/6/2019
GeekforGeeks
Summary
Node.js local modules are custom modules that you create within your application to organize, encapsulate, and reuse code. They help in maintaining a clean and modular codebase, improving both the maintainability and scalability of your application. By following best practices for local modules, you can build more structured and efficient Node.js applications.