1 说明

  • 模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的。一个 Node.js 文件就是一个模块,这个文件可能是JavaScript 代码、JSON 或者编译过的C/C++ 扩展。
  • Node.js 提供了 exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模块的接口,即所获取模块的 exports 对象。

2示例

代码示例

  • main.js
1
2
var hello = require('./hello');
hello.world();
  • hello.js
1
2
3
exports.world = function() {
console.log('Hello World');
}

暴露对象

1
2
3
4
5
6
7
8
9
10
11
//hello.js 
function Hello() {
var name;
this.setName = function(thyName) {
name = thyName;
};
this.sayHello = function() {
console.log('Hello ' + name);
};
};
module.exports = Hello;
1
2
3
4
5
//main.js 
var Hello = require('./hello');
hello = new Hello();
hello.setName('BYVoid');
hello.sayHello();

require过程