Node.js-2.模块

一、Node.js模块

每一个Node.js都是一个Node.js模块,包括JavaScript文件(.js)、JSON文本文件(.json)和二进制模块文件(.node)。

1. 模块的使用

编写一个模块:

在虚拟机桌面新建一个文件mymodule.js,输入如下代码并保存:

function hello() {

    console.log('Hello');

}

function world() {

    console.log('World');

}

这就是一个Node.js模块,但是怎么在其他模块中引入并使用这个模块呢?我们需要为模块提供对外的接口,这就要用到module.exports和exports。

我们可以这样写mymodul.js:

function hello() {

    console.log('Hello');

}


function world() {

    console.log('World');

}



exports.hello = hello;

exports.world = world;

在其他模块中,可以使用require(module_name);载入需要的模块,如,在虚拟机桌面新建index.js,输入如下代码并保存:

var hello = require('./mymodule'); // 也可以写作 var hello = require('./mymodule.js');

// 现在就可以使用mymodule.js中的函数了

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

也可以这样写mymodule.js:

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

module.exports = Hello;

此时,index.js就要改成这样:

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的关系可以表示成这样:

// 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

二、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>可以撤销发布自己发布过的某个版本代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值