Node in the exports module object believe that everyone must be not unfamiliar;
such as Studentmodule.js:
function () { console.log ("this is student module!" ); }
This is referred to in another module:
var student = require ('./studentmodule.js '// This is student module!
So here's the question: What is module.exports?
In fact Module.exports
, is the real interface,exports is just one of its auxiliary tools. The final return to the call Module.exports
is instead of exports.
All the properties and methods collected by the exports are Module.exports
assigned. Of course, There is a premise thatModule.exports
本身不具备任何属性和方法
。如果,
Module.exports
已经具备一些属性和方法,那么exports收集来的信息将被忽略。
Let's change the studentmodule.js.
Module.exports = "student module"function() { console.log ("this is student module!" ); }
We introduce this module in another JS file (the js file introduced here belongs to the sibling Introduction)
var student = Require (".. /studentmodule.js "//typeerror:object Student module! has no method ' student '
The error message here refers to the object student module! no student this method.
The student module ignores the student method that exports collects and returns a string of "student module". Your module does not necessarily have to return "instanced objects". Your module can be any legitimate JavaScript object--boolean, number, date, JSON, string, function, array, and so On.
Your module can be anything you set to it. If you do not explicitly Module.exports
set any properties and methods, then your module is exports set toModule.exports的
属性。
Here's A chestnut, Suppose you are a module is a class person.js:
function (name, age) { this. name = name; this. age = Age ; this function () { console.log (this. name + ' age: the. age);}; } ;
In another module this is introduced using:
var person = require ('./person.js '); var New Persion ("xiao ming",//name: Xiao Ming age:12
If your module is an array of arr.js:
Module.exports = ["apple", "banana", "orange"];
Introduced in other modules:
var arr = require ("./arr.js"); for (var i = 0; i < arr.length;; i++) { console.log (arr[i]);} // result Output: Apple,banana,orange
If you want your module to be a specific type just use Module.exports if you want your module to instantiate the object with Exports.
Module.exports is a true interface, and exports is just its secondary interface. It is recommended to export using exports, unless you intend to change from the original "instantiated object" to a type.
Reference: http://www.cnblogs.com/pigtail/archive/2013/01/14/2859555.html
Original: http://www.hacksparrow.com/node-js-exports-vs-module-exports.html
The difference between exports and module.exports in Nodejs