文章目录
1 module概述
1.1 module的简介
Node
程序由许多个模块组成,每个模块就是一个文件。Node
模块采用了CommonJS
规范。
根据CommonJS
规范,一个单独的文件就是一个模块。每一个模块都是一个单独的作用域,也就是说,在一个文件定义的变量(还包括函数和类),都是私有的,对其他文件是不可见的。
// example.js
var x = 5;
var addX = function(value) {
return value + x;
};
上面代码中,变量x
和函数addX
,是当前文件example.js
私有的,其他文件不可见。
如果想在多个文件分享变量,必须定义为global对象的属性。
global.warning = true;
上面代码的warning
变量,可以被所有文件读取
。当然,这样写法是不推荐的
。
CommonJS
规定,每个文件的对外接口是module.exports
对象。这个对象的所有属性和方法,都可以被其他文件导入。
var x = 5;
var addX = function(value) {
return value + x;
};
module.exports.x = x;
module.exports.addX = addX;
上面代码通过module.exports
对象,定义对外接口,输出变量x
和函数addX
。module.exports
对象是可以被其他文件导入的,它其实就是文件内部与外部通信的桥梁。require
方法用于在其他文件加载这个接口
var example = require('./example.js');
console.log(example.x); // 5
console.log(example.addX(1)); // 6
CommonJS
模块的特点如下
- 所有代码都运行在模块作用域,不会污染全局作用域。
- 模块可以多次加载,但是只会在
第一次加载时运行一次
,然后运行结果就被缓存
了,以后再加载,就直接读取缓存结果。要想让模块再次运行,必须清除缓存
。 - 模块加载的顺序,按照其在代码中出现的顺序。
1.2 module对象
每个模块内部,都有一个module
对象,代表当前模块。它有以下属性。
module.id
模块的识别符,通常是带有绝对路径的模块文件名。module.filename
模块的文件名,带有绝对路径。module.loaded
返回一个布尔值,表示模块是否已经完成加载。module.parent
返回一个对象,表示调用该模块的模块。module.children
返回一个数组,表示该模块要用到的其他模块。
下面是一个示例文件,最后一行输出module
变量。
// example.js
var jquery = require('jquery');
exports.$ = jquery;
console.log(module);
执行这个文件,命令行会输出如下信息。
{ id: '.',
exports: { '$': [Function] },
parent: null,
filename: '/path/to/example.js',
loaded: false,
children:
[ { id: '/path/to/node_modules/jquery/dist/jquery.js',
exports: [Function],
parent: [Circular],
filename: '/path/to/node_modules/jquery/dist/jquery.js',
loaded: true,
children: [],
paths: [Object] } ],
paths:
[ '/home/user/deleted/node_modules',
'/home/user/node_modules',
'/home/node_modules',
'/node_modules' ]
}
1.2.1 module.exports属性
module.exports
属性表示当前模块对外输出的接口,其他文件加载该模块,实际上就是读取module.exports
变量。
var EventEmitter = require('events').EventEmitter;
module.exports = new EventEmitter();
setTimeout(function() {
module.exports.emit('ready');
}, 1000);
上面模块会在加载后1秒
后,发出ready
事件。其他文件监听该事件,可以写成下面这样。
var a = require('./a');
a.on('ready', function() {
console.log('module a is ready');
});
1.2.2 exports变量
为了方便,Node
为每个模块提供一个exports
变量,指向module.exports
。这等同在每个模块头部,有一行这样的命令。
var exports = module.exports;
造成的结果是,在对外输出模块接口时,可以向exports
对象添加方法。
exports.area = function (r) {
return Math.PI * r * r;
};
exports.circumference = function (r) {
return 2 * Math.PI * r;
};
注意
,不能直接将exports
变量指向一个值,因为这样等于切断了exports与module.exports
的联系。
exports = function(x) {console.log(x)};
上面这样的写法是无效的,因为exports
不再指向module.exports
了。
下面的写法也是无效的。
exports.hello = function() {
return 'hello';
};
module.exports = 'Hello world';
上面代码中,hello
函数是无法对外输出
的,因为module.exports
被重新赋值了。
这意味着,如果一个模块的对外接口,就是一个单一的值,不能使用exports
输出,只能使用module.exports
输出。
module.exports = function (x){ console.log(x);};
注意
:如果你觉得,exports
与module.exports
之间的区别很难分清,一个简单的处理方法,就是放弃使用exports
,只使用module.exports
1.3 AMD规范与CommonJS规范的兼容性
CommonJS
规范加载模块是同步
的,也就是说,只有加载完成,才能执行后面的操作AMD
规范则是非同步加载模块
,允许指定回调函数- 由于
Node.js
主要用于服务器编程
,模块文件一般都已经存在于本地硬盘,所以加载起来比较快,不用考虑非同步加载的方式,所以CommonJS
规范比较适用。 - 如果是浏览器环境,要从服务器端加载模块,这时就必须采用非同步模式,因此浏览器端一般采用
AMD
规范。
AMD
规范使用define
方法定义模块,下面就是一个例子:
define(['package/lib'], function(lib){
function foo(){
lib.log('hello world!');
}
return {
foo: foo
};
});
AMD
规范允许输出的模块兼容CommonJS
规范,这时define
方法需要写成下面这样:
define(function (require, exports, module){
var someModule = require("someModule");
var anotherModule = require("anotherModule");
someModule.doTehAwesome();
anotherModule.doMoarAwesome();
exports.asplode = function (){
someModule.doTehAwesome();
anotherModule.doMoarAwesome();
};
});
1.4 require命令
1.4.1 基本用法
Node.js
使用CommonJS
模块规范,内置的require
命令用于加载模块文件。
require
命令的基本功能是,读入并执行一个JavaScript
文件,然后返回该模块的exports
对象。如果没有发现指定模块,会报错。
// example.js
var invisible = function () {
console.log("invisible");
}
exports.message = "hi";
exports.say = function () {
console.log(message);
}
运行下面的命令,可以输出exports
对象。
var example = require('./example.js');
example
// {
// message: "hi",
// say: [Function]
// }
如果模块输出的是一个函数
,那就不能定义在exports
对象上面,而要定义在module.exports
变量上面。
module.exports = function () {
console.log("hello world")
}
require('./example2.js')()
上面代码中,require
命令调用自身,等于是执行module.exports
,因此会输出 hello world
1.4.2 加载文件
require
命令用于加载文件,后缀名默认为.js
var foo = require('foo');
// 等同于
var foo = require('foo.js');
根据参数的不同格式,require
命令去不同路径寻找模块文件。
- 如果参数字符串以
“/”
开头,则表示加载的是一个位于绝对路径
的模块文件。比如,require('/home/marco/foo.js')
将加载/home/marco/foo.js
- 如果参数字符串以
“./”
开头,则表示加载的是一个位于相对路径
(跟当前执行脚本的位置相比)的模块文件。比如,require('./circle')
将加载当前脚本同一目录的circle.js
。 - 如果参数字符串不以
“./“或”/“
开头,则表示加载的是一个默认提供的核心模块
(位于Node的系统安装目录中),或者一个位于各级node_modules
目录的已安装模块(全局安装或局部安装)。
举例来说,脚本/home/user/projects/foo.js
执行了require('bar.js')
命令,Node
会依次搜索以下文件。
- /usr/local/lib/node/bar.js
- /home/user/projects/node_modules/bar.js
- /home/user/node_modules/bar.js
- /home/node_modules/bar.js
- /node_modules/bar.js
这样设计的目的是,使得不同的模块可以将所依赖的模块本地化。
- 如果参数字符串不以
“./“或”/“
开头,而且是一个路径,比如require('example-module/path/to/file')
,则将先找到example-module
的位置,然后再以它为参数,找到后续路径。 - 如果指定的模块文件没有发现,
Node
会尝试为文件名添加.js、.json、.node
后,再去搜索。.js
件会以文本格式的JavaScript
脚本文件解析,.json
文件会以JSON
格式的文本文件解析,.node
文件会以编译后的二进制文件解析。 - 如果想得到
require
命令加载的确切文件名,使用require.resolve()
方法。
1.4.3 加载目录
通常,我们会把相关的文件会放在一个目录里面,便于组织。这时,最好为该目录设置一个入口文件,让require
方法可以通过这个入口文件,加载整个目录。
在目录中放置一个package.json
文件,并且将入口文件写入main
字段。下面是一个例子。
// package.json
{ "name" : "some-library",
"main" : "./lib/some-library.js"
}
require
发现参数字符串指向一个目录以后,会自动查看该目录的package.json
文件,然后加载main
字段指定的入口文件
。如果package.json
文件没有main字段
,或者根本就没有package.json文件
,则会加载该目录下的index.js文件或index.node文件
。
如果没有package.json
文件那么加载规则则是:
将 X
当成目录,依次查找下面文件,只要其中有一个存在,就返回该文件,不再继续执行:
- X/package.json(main字段)
- X/index.js
- X/index.json
- X/index.node
1.4.4 require.main
require
方法有一个main属性
,可以用来判断模块是直接执行,还是被调用执行。
直接执行
的时候(node module.js
),require.main
属性指向模块本身
。
require.main === module
// true
调用执行
的时候(通过require加载该脚本执行),上面的表达式返回false
。
1.5 模块的缓存
第一次加载某个模块时,Node
会缓存该模块。以后再加载该模块,就直接从缓存取出该模块的exports
属性。
require('./example.js');
require('./example.js').message = "hello";
require('./example.js').message
// "hello"
上面代码中,连续三次使用require
命令,加载同一个模块。第二次加载的时候,为输出的对象添加了一个message
属性。但是第三次加载的时候,这个message
属性依然存在,这就证明require
命令并没有重新加载模块文件,而是输出了缓存。
如果想要多次执行某个模块,可以让该模块输出一个函数,然后每次require
这个模块的时候,重新执行一下输出的函数。
注意
,缓存是根据绝对路径识别模块
的,如果同样的模块名,但是保存在不同的路径,require
命令还是会重新加载该模块。
1.6 环境变量NODE_PATH
Node
执行一个脚本时,会先查看环境变量NODE_PATH
。它是一组以冒号分隔的绝对路径。
在其他位置找不到指定模块时,Node会去这些路径查找。
可以将NODE_PATH
添加到.bashrc
。
export NODE_PATH="/usr/local/lib/node"
所以,如果遇到复杂的相对路径,比如下面这样。
var myModule = require('../../../../lib/myModule');
有两种解决方法,一是将该文件加入node_modules
目录,二是修改NODE_PATH
环境变量,package.json
文件可以采用下面的写法。
{
"name": "node_path",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "NODE_PATH=lib node index.js"
},
"author": "",
"license": "ISC"
}
NODE_PATH
是历史遗留下来的一个路径解决方案,通常不应该使用,而应该使用node_modules
目录机制。
1.7 模块的循环加载
如果发生模块的循环加载,即A加载B,B又加载A,则B将加载A的不完整版本。
// a.js
exports.x = 'a1';
console.log('a.js ', require('./b.js').x);
exports.x = 'a2';
// b.js
exports.x = 'b1';
console.log('b.js ', require('./a.js').x);
exports.x = 'b2';
// main.js
console.log('main.js ', require('./a.js').x);
console.log('main.js ', require('./b.js').x);
上面代码是三个JavaScript文件
。其中,a.js加载了b.js,而b.js又加载a.js。这时,Node
返回a.js的不完整版本,所以执行结果如下。
$ node main.js
b.js a1
a.js b2
main.js a2
main.js b2
修改main.js,再次加载a.js和b.js。
// main.js
console.log('main.js ', require('./a.js').x);
console.log('main.js ', require('./b.js').x);
console.log('main.js ', require('./a.js').x);
console.log('main.js ', require('./b.js').x);
执行上面代码,结果如下。
$ node main.js
b.js a1
a.js b2
main.js a2
main.js b2
main.js a2
main.js b2
上面代码中,第二次加载a.js和b.js时,会直接从缓存读取exports
属性,所以a.js和b.js内部的console.log语句都不会执行了。
1.8 模块的加载机制
CommonJS
模块的加载机制是,输入的是被输出的值的拷贝。也就是说,一旦输出一个值,模块内部的变化就影响不到这个值。请看下面这个例子。
下面是一个模块文件lib.js
// lib.js
var counter = 3;
function incCounter() {
counter++;
}
module.exports = {
counter: counter,
incCounter: incCounter,
};
上面代码输出内部变量counter
和改写这个变量的内部方法incCounter
然后,加载上面的模块。
// main.js
var counter = require('./lib').counter;
var incCounter = require('./lib').incCounter;
console.log(counter); // 3
incCounter();
console.log(counter); // 3
上面代码说明,counter
输出以后,lib.js模块内部的变化就影响不到counter了。