当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Node.js模块系统

Node.js模块系统

2020年03月11日  | 移动技术网IT编程  | 我要评论

模块是node.js 应用程序的基本组成部分,文件和模块是一一对应的。

一个 node.js 文件就是一个模块,这个文件可能是javascript 代码、json 或者编译过的c/c++ 扩展。

 

接下来我们来尝试创建一个模块

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

首先创建main.js

//引入了当前目录下的 cyy.js 文件(./ 为当前目录,node.js 默认后缀为 js)
var cyy=require("./cyy");
cyy.sing();

接下来创建cyy.js

exports.sing=function(){
    console.log("cyy is singing now~");
}

打印结果:

 

 

把一个对象封装到模块中

那么把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修改为:

//引入了当前目录下的 cyy.js 文件(./ 为当前目录,node.js 默认后缀为 js)
var cyy=require("./cyy");
cyy=new cyy();
cyy.sing("hhh~");
cyy.setname("new cyy");
cyy.getname();

打印结果:

 

 在外部引用该模块时,其接口对象就是要输出的cyy对象本身,而不是原先的 exports。

 

服务器的模块

 模块内部加载优先级:

1、从文件模块的缓存中加载

2、从原生模块加载

3、从文件中加载

 

require方法接受以下几种参数的传递:

  • http、fs、path等,原生模块。
  • ./mod或../mod,相对路径的文件模块。
  • /pathtomodule/mod,绝对路径的文件模块。
  • mod,非原生模块的文件模块。

 

exports 和 module.exports 的使用
如果要对外暴露属性或方法,就用 exports 就行;
要暴露对象(类似class,包含了很多属性和方法),就用 module.exports。

 

不建议同时使用 exports 和 module.exports。

如果先使用 exports 对外暴露属性或方法,再使用 module.exports 暴露对象,会使得 exports 上暴露的属性或者方法失效。

原因在于,exports 仅仅是 module.exports 的一个引用。

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网