Nodejs 模块系统


创建模块 hello.js 

exports.world = function(){
    console.log("hello world");
}

引入模块samp9.js

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

执行

PS E:\study\nodejs\demo1> node .\samp9.js
hello world

将对象分装成模块

hello2.js

function Hello(){
    var name;
    this.setName = function(theName){
        name = theName;
    };
    this.sayHello = function(){
        console.log("Hello " + name);
    };
};

module.exports = Hello;

samp10.js

var Hello = require("./hello2");
hello = new Hello();
hello.setName("nick");
hello.sayHello();

执行:

PS E:\study\nodejs\demo1> node .\samp10.js
Hello nick

相关