Node.js-2.模塊

1、Node.js模塊

每個Node.js都是一個Node.js模塊,包括JavaScript文件(.js)、JSON文本文件(.json)和二進制模塊文件(.node)。html

1. 模塊的使用

編寫一個模塊:node

在虛擬機桌面新建一個文件mymodule.js,輸入以下代碼並保存:git

function hello() {

    console.log('Hello');

}

function world() {

    console.log('World');

}

這就是一個Node.js模塊,可是怎麼在其餘模塊中引入並使用這個模塊呢?咱們須要爲模塊提供對外的接口,這就要用到module.exports和exports。github

咱們能夠這樣寫mymodul.js:web

function hello() {

    console.log('Hello');

}


function world() {

    console.log('World');

}



exports.hello = hello;

exports.world = world;

在其餘模塊中,可使用require(module_name);載入須要的模塊,如,在虛擬機桌面新建index.js,輸入以下代碼並保存:express

var hello = require('./mymodule'); // 也能夠寫做 var hello = require('./mymodule.js');

// 如今就可使用mymodule.js中的函數了

hello.hello(); // >> Hello
hello.world(); // >> World

也能夠這樣寫mymodule.js:apache

function Hello() {
    this.hello = function() {
        console.log('Hello');
    };
    this.world = function() {
        console.log('World');
    };
}

module.exports = Hello;

此時,index.js就要改爲這樣:npm

var Hello = require('./mymodule');
var hello = new Hello();
hello.hello(); // >> Hello
hello.world(); // >> World

2. module.exports和exports

module是一個對象,每一個模塊中都有一個module對象,module是當前模塊的一個引用。module.exports對象是Module系統建立的,而exports能夠看做是對module.exports對象的一個引用。在模塊中require另外一個模塊時,以module.exports的值爲準,由於有的狀況下,module.exports和exports它們的值是不一樣的。module.exports和exports的關係能夠表示成這樣:json

// module.exports和exports相同的狀況
var m = {};        // 表示 module
var e = m.e = {};  // e 表示 exports, m.e 表示 module.exports
m.e.a = 5;
e.b = 6;
console.log(m.e);  // Object { a: 5, b: 6 }
console.log(e);    // Object { a: 5, b: 6 }
// module.exports和exports不一樣的狀況
var m = {};        // 表示 module
var e = m.e = {};  // e 表示 exports, m.e 表示 module.exports
m.e = { c: 9 };    // m.e(module.exports)引用的對象被改了
e.d = 10;
console.log(m.e);  // Object { c: 9 }
console.log(e);    // Object { d: 10 }

Node.js模塊系統數組

require,exports,module.exports區別

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

建立模塊
在 Node.js 中,建立一個模塊很是簡單,以下咱們建立一個 'main.js' 文件,代碼以下:

var hello = require('./hello');
hello.world();

以上實例中,代碼 require('./hello') 引入了當前目錄下的hello.js文件(./ 爲當前目錄,node.js默認後綴爲js)。

Node.js 提供了exports 和 require 兩個對象,其中 exports 是模塊公開的接口,require 用於從外部獲取一個模塊的接口,即所獲取模塊的 exports 對象。
接下來咱們就來建立hello.js文件,代碼以下:

exports.world = function() {
  console.log('Hello World');
}

在以上示例中,hello.js 經過 exports 對象把 world 做爲模塊的訪問接口,在 main.js 中經過 require('./hello') 加載這個模塊,而後就能夠直接訪 問 hello.js 中 exports 對象的成員函數了。

有時候咱們只是想把一個對象封裝到模塊中,格式以下:

module.exports = function() {
  // ...
}

例如:

//hello.js 
function Hello() { 
    var name; 
    this.setName = function(thyName) { 
        name = thyName; 
    }; 
    this.sayHello = function() { 
        console.log('Hello ' + name); 
    }; 
}; 
module.exports = Hello;

這樣就能夠直接得到這個對象了:

//main.js 
var Hello = require('./hello'); 
hello = new Hello(); 
hello.setName('BYVoid'); 
hello.sayHello();

模塊接口的惟一變化是使用 module.exports = Hello 代替了exports.world = function(){}。 在外部引用該模塊時,其接口對象就是要輸出的 Hello 對象自己,而不是原先的 exports

2、Node.js包

1. 包

包用於管理多個模塊及其依賴關係,能夠對多個模塊進行封裝,包的根目錄必須包含package.json文件,package.json文件是CommonJS規範用於描述包的文件,符合CommonJS規範的package.json文件應該包含如下字段:

name:包名。包名是惟一的,只能包含小寫字母、數字和下劃線。

version:包版本號。

description:包說明。

keywords:關鍵字數組。用於搜索。

homepage:項目主頁。

bugs:提交bug的地址。

license:許可證。

maintainers:維護者數組。

contributors:貢獻者數組。

repositories:項目倉庫託管地址數組。

dependencies:包依賴。

下面是一個package.json示例:

{

    "name": "shiyanlou",

    "description": "Shiyanlou test package.",

    "version": "0.1.0",

    "keywords": [

        "shiyanlou",

        "nodejs"

     ],

    "maintainers": [{

        "name": "test",

        "email": "test@shiyanlou.com"

    }],

    "contributors": [{

        "name": "test",

        "web": "http://www.shiyanlou.com/"

    }],

    "bugs": {

        "mail": "test@shiyanlou.com",

        "web": "http://www.shiyanlou.com/"

    },

    "licenses": [{

        "type": "Apache License v2",

        "url": "http://www.apache.org/licenses/apache2.html"

    }],

    "repositories": [{

        "type": "git",

        "url": "http://github.com/test/test.git"

    }],

    "dependencies": { 

        "webkit": "1.2",

        "ssl": { 

            "gnutls": ["1.0", "2.0"],

            "openssl": "0.9.8"

        }

    }

}

package.json 位於模塊的目錄下,用於定義包的屬性。接下來讓咱們來看下 express 包的 package.json 文件,位於 node_modules/express/package.json

2. npm包管理工具

因爲新版的nodejs已經集成了npm,因此以前npm也一併安裝好了。一樣能夠經過輸入 "npm -v" 來測試是否成功安裝。命令以下,出現版本提示表示安裝成功:

MacdeMacBook-Pro-3:node mac$ npm -v
3.9.3

使用 npm 命令安裝模塊
npm 安裝 Node.js 模塊語法格式以下:

$ npm install <Module Name>

如下實例,咱們使用 npm 命令安裝經常使用的 Node.js web框架模塊 express:

$ npm install express

安裝好以後,express 包就放在了工程目錄下的 node_modules 目錄中,所以在代碼中只須要經過 require('express') 的方式就好,無需指定第三方包路徑。

var express = require('express');

全局安裝與本地安裝
npm 的包安裝分爲本地安裝(local)、全局安裝(global)兩種,從敲的命令行來看,差異只是有沒有-g而已,好比

npm install express          # 本地安裝
npm install express -g   # 全局安裝

若是出現如下錯誤:

npm err! Error: connect ECONNREFUSED 127.0.0.1:8087

解決辦法爲:

$ npm config set proxy null

本地安裝

  1. 將安裝包放在 ./node_modules 下(運行 npm 命令時所在的目錄),若是沒有 node_modules 目錄,會在當前執行 npm 命令的目錄下生成 node_modules 目錄。

  2. 能夠經過 require() 來引入本地安裝的包。

全局安裝

  1. 將安裝包放在 /usr/local 下或者你 node 的安裝目錄。

  2. 能夠直接在命令行裏使用。
    若是你但願具有二者功能,則須要在兩個地方安裝它或使用 npm link。

接下來咱們使用全局方式安裝 express

$ npm install express -g

安裝過程輸出以下內容,第一行輸出了模塊的版本號及安裝位置。

express@4.13.3 node_modules/express
├── escape-html@1.0.2
├── range-parser@1.0.2
├── merge-descriptors@1.0.0
├── array-flatten@1.1.1
├── cookie@0.1.3
├── utils-merge@1.0.0
├── parseurl@1.3.0
├── cookie-signature@1.0.6
├── methods@1.1.1
├── fresh@0.3.0
├── vary@1.0.1
├── path-to-regexp@0.1.7
├── content-type@1.0.1
├── etag@1.7.0
├── serve-static@1.10.0
├── content-disposition@0.5.0
├── depd@1.0.1
├── qs@4.0.0
├── finalhandler@0.4.0 (unpipe@1.0.0)
├── on-finished@2.3.0 (ee-first@1.1.1)
├── proxy-addr@1.0.8 (forwarded@0.1.0, ipaddr.js@1.0.1)
├── debug@2.2.0 (ms@0.7.1)
├── type-is@1.6.8 (media-typer@0.3.0, mime-types@2.1.6)
├── accepts@1.2.12 (negotiator@0.5.3, mime-types@2.1.6)
└── send@0.13.0 (destroy@1.0.3, statuses@1.2.1, ms@0.7.1, mime@1.3.4, http-errors@1.3.1)

你可使用如下命令來查看全部全局安裝的模塊:

$ npm ls -g

卸載模塊
咱們可使用如下命令來卸載 Node.js 模塊。

$ npm uninstall express

卸載後,你能夠到 /node_modules/ 目錄下查看包是否還存在,或者使用如下命令查看:

$ npm ls

更新模塊
咱們可使用如下命令更新模塊:

$ npm update express

搜索模塊
使用如下來搜索模塊:

$ npm search express

建立模塊

建立模塊,package.json 文件是必不可少的。咱們可使用 NPM 生成 package.json 文件,生成的文件包含了基本的結果。

$ npm init

NPM 經常使用命令除了本章介紹的部分外,NPM還提供了不少功能,package.json裏也有不少其它有用的字段。除了能夠在npmjs.org/doc/查看官方文檔外,這裏再介紹一些NPM經常使用命令。NPM提供了不少命令,例如install和publish,使用npm help可查看全部命令。NPM提供了不少命令,例如install和publish,使用npm help可查看全部命令。使用npm help <command>可查看某條命令的詳細幫助,例如npm help install。在package.json所在目錄下使用npm install . -g可先在本地安裝當前命令行程序,可用於發佈前的本地測試。使用npm update <package>能夠把當前目錄下node_modules子目錄裏邊的對應模塊更新至最新版本。使用npm update <package> -g能夠把全局安裝的對應命令行程序更新至最新版。使用npm cache clear能夠清空NPM本地緩存,用於對付使用相同版本號發佈新版本代碼的人。使用npm unpublish <package>@<version>能夠撤銷發佈本身發佈過的某個版本代碼。

相關文章
相關標籤/搜索