The CommonJs Module system is use to share the object or properties in node.js. Since Javaascript runs program in global scope. CommonJs Module is one of the best way for creating and sharing namespace in the javascript environment.
Here below given an example to export a function in node.js.
//person.js
/**
* Created by deepak.m.shrma@gmail.com on 11/1/15.
*/
function Person(name, age, desc) {
var _name = name || 'no_name',
_age = age || 1 || 'just_born',
_desc = desc || 'i am just a moron';
function getInformation() {
return {
name: _name,
age: _age,
desc: _desc
}
}
return {
get: getInformation
}
}
module.exports = Person;
Here module is representing current module you are in. module.exports is object that module will export. In above example, It is representing a constructor of the Person function. You can export multiple properties by module.exports.
For example, You can export multiple function and attributes:
//multiple-properties.js
/**
* Created by deepak.m.shrma@gmail.com on 11/1/15.
*/
function fun1() {
console.log('this is func 1');
}
function fun2() {
console.log('this is func 2');
}
function fun3() {
console.log('this is func 3');
}
module.exports.fun1 = fun1;
module.exports.fun2 = fun2;
module.exports.fun3 = fun3;
module.exports.val = 'some_value';
//implementation.js
var myModule2 = require('./multiple-properties');
myModule2.fun1(); // -> this is func 1
myModule2.fun2(); // -> this is func 2
console.log(myModule2.val); // -> some_value
This one is for testing..
ReplyDelete