模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的。node
一个 Node.js 文件就是一个模块,这个文件多是JavaScript 代码、JSON 或者编译过的C/C++ 扩展。缓存
接下来咱们来尝试建立一个模块服务器
Node.js 提供了 exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模块的接口,即所获取模块的 exports 对象。ui
首先建立main.jsthis
//引入了当前目录下的 cyy.js 文件(./ 为当前目录,node.js 默认后缀为 js) var cyy=require("./cyy"); cyy.sing();
接下来建立cyy.jsspa
exports.sing=function(){ console.log("cyy is singing now~"); }
打印结果:3d
把一个对象封装到模块中code
那么把cyy.js修改成:对象
function cyy(){ var name; this.sing=function(song){ console.log("cyy is sing "+song); } this.setName=function(name){ this.name=name; } this.getName=function(){ console.log(this.name); } } module.exports=cyy;
把main.js修改成:blog
//引入了当前目录下的 cyy.js 文件(./ 为当前目录,node.js 默认后缀为 js) var cyy=require("./cyy"); cyy=new cyy(); cyy.sing("hhh~"); cyy.setName("new cyy"); cyy.getName();
打印结果:
在外部引用该模块时,其接口对象就是要输出的cyy对象自己,而不是原先的 exports。
服务器的模块
模块内部加载优先级:
一、从文件模块的缓存中加载
二、从原生模块加载
三、从文件中加载
require方法接受如下几种参数的传递:
exports 和 module.exports 的使用
若是要对外暴露属性或方法,就用 exports 就行;
要暴露对象(相似class,包含了不少属性和方法),就用 module.exports。
不建议同时使用 exports 和 module.exports。
若是先使用 exports 对外暴露属性或方法,再使用 module.exports 暴露对象,会使得 exports 上暴露的属性或者方法失效。
缘由在于,exports 仅仅是 module.exports 的一个引用。