- Sep 30, 2018
- admin
- 0
Export Module in Node.js:
Node.js also facilitates its users to create their own modules using export keyword. The module.exports or exports object is a special type of object which is used to expose a function, object or variable as a module in Node.js.
● Export Literals:
If a string literal is assigned to the module.exports or exports object, the string literal will be exposed as a module.
● Export Object:
If a property or method is assigned to the module.exports or exports object, than that property or method will be exposed as a module.
● Export Function:
If a function is assigned to the module.exports or exports object, than that function will be exposed as a module.
● Export function as a class:
If a class is assigned to the module.exports or exports object, than that class will be exposed as a module.
Including a Local Module in an application:
To include a local module in an application, Node.js require() function with the path of the module is used.
Syntax:
var variable_name = require(‘module_path’);
Example:
Module: mod.js
var mod = {
msg: function (msg) {
console.log(‘Msg: ‘ + msg);
},
};
module.exports = mod
Application: hello.js
var hello = require(‘/home/Desktop/modu.js’);
hello.msg(‘HELLO’);
OUTPUT:
Msg: HELLO