NodeJs 提供了 exports 和 require 两个对象

Node.js 提供了 exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模块的接口,即所获取模块的 exports 对象。

创建一个hello.js文件,代码如下

exports.world = function() {
  console.log('Hello World');
}

在 Node.js 中,创建一个模块非常简单,如下我们创建一个 main.js 文件,代码如下:

var hello = require('./hello');
hello.world(); 

如上代码有一个问题,上面代码不能返回对象本身,要重新调用(不能hello()代替hello.word()方法),如果我们想封装一个对象在模块中,代码如下:

//hello.js 
function Hello() { 
    var name; 
    this.setName = function(thyName) { 
        name = thyName; 
    }; 
    this.sayHello = function() { 
        console.log('Hello ' + name); 
    }; 
}; 
module.exports = Hello; // module.exports 可以返回对象本身

使用方法,代码如下:

//main.js 
var Hello = require('./hello'); 
hello = new Hello(); 
hello.setName('BYVoid'); 
hello.sayHello();