Answers for "Local Module: Export and Log"

0

Local Module: Export and Log

//// Writing Simple LOCAL Module 
// Let's write simple logging module which logs the information, 
// warning or error to the console.
// In Node.js, module is placed in separate JavaScript file.
// So, create a Log.js file and write the following code in it.
// name of file Log.js Copy
const 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

// In the above logging module we created an object with
// three functions - info(), warning() and error(). 
// Ending assigned object to module.exports. 
// module.exports in above ex exposes log object as a module.

// The module.exports is a special object which is included 
// in every JS file in the Node.js application by default. 
// Use module.exports or exports to expose a function, 
// object or variable as a module in Node.js.

// Now, let's see how to use the above logging module in our application.

// Loading Local Module
// To use local modules in your application, 
// you need to load it using require() function 
// in the same way as core module. 
// However, you need to specify the path of JavaScript file of the module.


const myLogModule = require('./Log.js');

myLogModule.info('Node.js started');

// In the above example, app.js is using log module. 
// First loads logging module using require() function 
// and specified path where logging module is stored. 
// Logging module is contained in Log.js file in the root folder. 
// So, we have specified the path './Log.js' in the require() function.
// The '.' denotes a root folder.

// The require() function returns a log object because logging 
// module exposes an object in Log.js using module.exports.
// So now you can use logging module as an object and call 
// any of its functions using dot notation 
// e.g myLogModule.info() or myLogModule.warning() or myLogModule.error()

// Run the above example using command prompt (in Windows) as shown below.

C:\> node app.js
Info: Node.js started
Posted by: Guest on July-08-2021

Code answers related to "Local Module: Export and Log"

Code answers related to "Javascript"

Browse Popular Code Answers by Language