1//// Writing Simple LOCAL Module
2// Let's write simple logging module which logs the information,
3// warning or error to the console.
4// In Node.js, module is placed in separate JavaScript file.
5// So, create a Log.js file and write the following code in it.
6// name of file Log.js Copy
7const log = {
8 info: function (info) {
9 console.log('Info: ' + info);
10 },
11 warning:function (warning) {
12 console.log('Warning: ' + warning);
13 },
14 error:function (error) {
15 console.log('Error: ' + error);
16 }
17 };
18
19module.exports = log
20
21// In the above logging module we created an object with
22// three functions - info(), warning() and error().
23// Ending assigned object to module.exports.
24// module.exports in above ex exposes log object as a module.
25
26// The module.exports is a special object which is included
27// in every JS file in the Node.js application by default.
28// Use module.exports or exports to expose a function,
29// object or variable as a module in Node.js.
30
31// Now, let's see how to use the above logging module in our application.
32
33// Loading Local Module
34// To use local modules in your application,
35// you need to load it using require() function
36// in the same way as core module.
37// However, you need to specify the path of JavaScript file of the module.
38
39
40const myLogModule = require('./Log.js');
41
42myLogModule.info('Node.js started');
43
44// In the above example, app.js is using log module.
45// First loads logging module using require() function
46// and specified path where logging module is stored.
47// Logging module is contained in Log.js file in the root folder.
48// So, we have specified the path './Log.js' in the require() function.
49// The '.' denotes a root folder.
50
51// The require() function returns a log object because logging
52// module exposes an object in Log.js using module.exports.
53// So now you can use logging module as an object and call
54// any of its functions using dot notation
55// e.g myLogModule.info() or myLogModule.warning() or myLogModule.error()
56
57// Run the above example using command prompt (in Windows) as shown below.
58
59C:\> node app.js
60Info: Node.js started