目录
什么是模块?模块系统?
之前已经说过模块的安装注册以及Http模块的简单使用,那么什么是模块呢?模块就相当于Node.js中的一个文件。为了实现文件之间的相互调用,所以Node.js提供了一个模块系统。
模块类型
模块可以分为原生模块和文件模块。模块的加载以及模块间的优先级如下图所示:
自定义模块
- 直接暴露属性、方法
- hello.js文件:
exports.field = "Hello World";
exports.method1 = function() {
console.log("This is method1");
}
- server.js文件
var Hello = require("./hello");
console.log(Hello.field);
Hello.method1();
2.暴露对象
- hello.js文件
function hello() {
var name;
this.setName = function(s) {
name = s;
};
this.getName = function() {
console.log(name);
};
}
module.exports = hello;
- server.js文件
var Hello = require("./hello");
var hello = new Hello();
hello.setName("Hello World");
hello.getName();