/*
Nodejs模块系统
为了让Nodejs的文件可以相互调用,nodejs提供了一个简单的模块系统
模块是nodejs应用程序的基本组成部分,文件和模块是一一对应的,换言之一个nodejs就是一个模块,这个文件可能是
javascript代码、Json或者编译过的c/c++ 扩展
//创建一个简单的模块
var hello = require("./hello");
hello.world();
require("./hello")是引入了当前目录下的hello.js文件
Nodejs提供了exports和require两个对象。其中exports是模块的公开的接口,require是用于从外部获取一个模块的接口
,即所获取模块的exports对象
创建hello.js
exports.world = function(){
console.log("Hello World");
}
hello.js是通过exports对象把world作为模块的访问接口,在其他加载hello.js的地方,就可以直接访问exports对象了
如何把对象封装到模块中呢?
module.exports = function(){
}
栗子:
//sayhell.js
function hello(){
var name ;
this.setName= function(thyName){
name=thyName;
};
this.sayHello = function(){
console.log('Hello'+name);
};
};
module.exports=hello;
使用sayhell.js模块
var hello = requrie("./sayhello");
hello = new SayHello();
hello.setName("LILI");
hello.sayHello();
模块接口的唯一变化是使用module.exports=Hello代替了exports.world=function(){}。在外部引用该模块时,
其接口对象就是要输出Hello对象本身,而不是原先的exports
服务端的模块放在哪里呢?
nodejs中自带了一个叫做http的模块,我们在我们的代码中请求它并把返回值赋给一个本地变量,
这样我们的本地变量变成了一个拥有所有 http模块的公共方法的对象
*/
Nodejs模块系统
为了让Nodejs的文件可以相互调用,nodejs提供了一个简单的模块系统
模块是nodejs应用程序的基本组成部分,文件和模块是一一对应的,换言之一个nodejs就是一个模块,这个文件可能是
javascript代码、Json或者编译过的c/c++ 扩展
//创建一个简单的模块
var hello = require("./hello");
hello.world();
require("./hello")是引入了当前目录下的hello.js文件
Nodejs提供了exports和require两个对象。其中exports是模块的公开的接口,require是用于从外部获取一个模块的接口
,即所获取模块的exports对象
创建hello.js
exports.world = function(){
console.log("Hello World");
}
hello.js是通过exports对象把world作为模块的访问接口,在其他加载hello.js的地方,就可以直接访问exports对象了
如何把对象封装到模块中呢?
module.exports = function(){
}
栗子:
//sayhell.js
function hello(){
var name ;
this.setName= function(thyName){
name=thyName;
};
this.sayHello = function(){
console.log('Hello'+name);
};
};
module.exports=hello;
使用sayhell.js模块
var hello = requrie("./sayhello");
hello = new SayHello();
hello.setName("LILI");
hello.sayHello();
模块接口的唯一变化是使用module.exports=Hello代替了exports.world=function(){}。在外部引用该模块时,
其接口对象就是要输出Hello对象本身,而不是原先的exports
服务端的模块放在哪里呢?
nodejs中自带了一个叫做http的模块,我们在我们的代码中请求它并把返回值赋给一个本地变量,
这样我们的本地变量变成了一个拥有所有 http模块的公共方法的对象
*/