在写node.js代码时,我们经常需要自己写模块(module)。同时还需要在模块最后写好模块接口,声明这个模块对外暴露什么内容。实际上,node.js的模块接口有多种不同写法。这里作者对此做了个简单的总结。

返回一个JSON Object

如下代码是一个简单的示例。

var exp = { 
  "version": "1.0.0", 
  "function1": null, 
  "module1": null,
};
module.exports = exp;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

这种方式可以用于返回一些全局共享的常量或者变量,例如

// MATH.js
var MATH = {
	"pi": 3.14,
	"e": 2.72,
};
module.exports = MATH;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

调用方式为

var MATH = require("./MATH")
console.log(MATH.pi);
  • 1.
  • 2.

这种方式还可以用于返回几个require的其他模块,可以实现一次require多个模块

// module_collection.js
var module_collection = {
  "module1": require("./module1"),
  "module2": require("./module2"),
};
module.exports = module_collection;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

调用方式为

var module_collection = require("./module_collection");
var module1 = module_collection.module1;
var module2 = module_collection.module2;
// Do something with module1 and module2
  • 1.
  • 2.
  • 3.
  • 4.

其实这种方式还有个变种,如下,通常可以返回几个函数

// functions.js
var func1 = function() {
  console.log("func1");
};
var func2 = function() {
	console.log("func2");
};
exports.function1 = func1;
exports.function2 = func2;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

调用方式为

var functions = require("./functions");
functions.function1();
functions.function2();
  • 1.
  • 2.
  • 3.

返回一个构造函数,也就是一个类

如下是一个简单的示例。

// CLASS.js
var CLASS = function(args) {
  this.args = args;
}
CLASS.prototype.func = function() {
  console.log("CLASS.func");
  console.log(this.args);
};
module.exports = CLASS;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

调用方法为

var CLASS = require("./CLASS")
var c = new CLASS("arguments");
  • 1.
  • 2.

返回一个普通函数

如下是一个简单的示例

unc.js
var func = function() {
  console.log("this is a testing function");
};
module.exports = func;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

调用方法为

var func = require("./func");
func();
  • 1.
  • 2.

返回一个对象object

如下是一个简单的示例

// CLASS.js
var CLASS = function() {
  this.say_hello = "hello";
};
CLASS.prototype.func = function() {
  console.log("I say " + this.say_hello);
};
module.exports = new CLASS();
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

调用方法为

var obj = require("./CLASS");
obj.func();
  • 1.
  • 2.

有时候我们需要模块返回一个单例 singleton. 可以利用上面的方式1和方式4来实现。也就是如下两种形式

// MATH.js
var MATH = {
  "pi": 3.14,
  "e": 2.72,
};
module.exports = MATH;

// CLASS.js
var CLASS = function() {
  this.say_hello = "hello";
};
CLASS.prototype.func = function() {
  console.log("I say " + this.say_hello);
};
module.exports = new CLASS();
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.