什麼是模塊?模塊系統?
之前已經說過模塊的安裝註冊以及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();