Node.js Local Modules: Create and Use Custom Modules for Better Code Organization
Learn how to create and use local modules in Node.js to enhance code organization and reusability. This guide covers creating a custom module, defining a log object, and exporting it for use in your project.
Node.js Local Module
Local modules are created within your project for specific functionalities. They enhance code organization and reusability and are not published to the public registry (unlike npm packages).
Creating a Local Module (Log.js)
- File Creation: Create a file named
Log.js
. - Module Object: Define an object (
log
) with functions for logging (info, warning, error). - Exporting the Module: Use
module.exports = log
to expose the log object as the module.
Log.js
var log = {
info: function (info) {
console.log('Info: ' + info);
},
warning: function (warning) {
console.log('Warning: ' + warning);
},
error: function (error) {
console.log('Error: ' + error);
}
};
module.exports = log;
Using a Local Module (app.js)
- Require Statement: Use
var myLogModule = require('./Log.js')
to import the module from./Log.js
(current directory). - Using the Module: Access the exposed object's methods using dot notation (e.g.,
myLogModule.info('Node.js started')
).
app.js
var myLogModule = require('./Log.js');
myLogModule.info('Node.js started');
Key Points
module.exports
is a special object for exporting functionality from a module.- The
require
function is used to import modules into your application. - The path in
require
specifies the location of the module file relative to the current file.
Additional Considerations
- You can export functions, variables, or even classes using
module.exports
. - Local modules can have dependencies on other local modules or core Node.js modules.
- For complex projects, consider structuring modules in folders for better organization.
By effectively utilizing local modules, you can create well-structured, maintainable, and reusable Node.js applications.
Running the Example
Run the above example using the command prompt (in Windows) as shown below:
C:\> node app.js
Info: Node.js started
Thus, you can create a local module using module.exports
and use it in your application.