nodeJS基礎:模塊系統

1. node JS 模塊介紹

爲了讓Node.js的文件能夠相互調用,Node.js提供了一個簡單的模塊系統。node

模塊是Node.js 應用程序的基本組成部分,文件和模塊是一一對應的。換言之,一個 Node.js 文件就是一個模塊,這個文件多是JavaScript 代碼、JSON 或者編譯過的C/C++ 擴展。函數

2. 建立模塊

Node.js 提供了exports 和 require 兩個對象,其中 exports 是模塊公開的接口,require 用於從外部獲取一個模塊的接口,即所獲取模塊的 exports 對象。 ui

實例:備註,在如下實例中 main.js 與 hello.js 都是處於同一文件夾下spa

// main.js

// 1. require('./hello') 引入了當前目錄下的hello.js文件(./ 爲當前目錄,node.js默認後綴爲js)。
var hello = require("./hello");

//2. 使用模塊
hello.hello("gaoxiong")
// hello.js

// 寫法1
module.exports.hello = function(name){
    console.log(name);
};

// 寫法2
exports.hello = function(name){
    console.log(name);
}

// 寫法1,2都是能夠的

在終端執行:node main.js 會打印 gaoxiong,不知道你有沒有留意上面,在調用模塊方法時時經過 hello.hello(params);這是爲何呢?咱們在hello.js中 暴露出的不是一個函數嗎?錯了!!!實際上這就牽扯到了如下暴露方法的區別code

  • exports:只能暴露出一個對象,無論你暴露出什麼,它返回的老是一個對象,對象中包含你所要暴露的信息
  • module.exports能暴露出任意數據類型

驗證:對象

//第一種狀況
//
main.js var hello = require("./hello"); console.log(hello); // hello.js exports.string = "fdfffd"; conosle.log 結果: { string: 'fdfffd' }
// main.js
var hello = require("./hello");
console.log(hello);

// hello.js
module.exports.string = "fdfffd";

// console.log()結果
{ string: 'fdfffd'}
// main.js
var hello = require("./hello");
console.log(hello);

// hello.js
module.exports = "fdfffd";

//conosle.log() 結果
fdfffd
// main.js
var hello = require("./hello");
console.log(hello);

// hello.js
exports = "fdfffd";
 
// conosle.log()結果 => 一個空對象

{}

 

對象上面四個狀況能夠得出:blog

module.exports.[name] = [xxx]  與 exports.[name]  都是返回一個對象 對象中有 name 屬性接口

而module.exports = [xxx]  返回實際的數據類型    而 exports = [xxx]  返回一個空對象:不起做用的空對象ip

相關文章
相關標籤/搜索