Node应用由模块组成,采用CommonJS模块规范。javascript
根据这个规范,每一个文件就是一个模块,有本身的做用域。在一个文件里面定义的变量、函数、类,都是私有的,对其余文件不可见。html
// example.js var x = 5; var addX = function (value) { return value + x; };
上面代码中,变量x
和函数addX
,是当前文件example.js
私有的,其余文件不可见。java
若是想在多个文件分享变量,必须定义为global
对象的属性。node
global.warning = true;
上面代码的warning
变量,能够被全部文件读取。固然,这样写法是不推荐的。jquery
CommonJS规范规定,每一个模块内部,module
变量表明当前模块。这个变量是一个对象,它的exports
属性(即module.exports
)是对外的接口。加载某个模块,实际上是加载该模块的module.exports
属性。编程
var x = 5; var addX = function (value) { return value + x; }; module.exports.x = x; module.exports.addX = addX;
上面代码经过module.exports
输出变量x
和函数addX
。json
require
方法用于加载模块。数组
var example = require('./example.js'); console.log(example.x); // 5 console.log(example.addX(1)); // 6
require
方法的详细解释参见《Require命令》一节。浏览器
CommonJS模块的特色以下。缓存
Node内部提供一个Module
构建函数。全部模块都是Module
的实例。
function Module(id, parent) { this.id = id; this.exports = {}; this.parent = parent; // ...
每一个模块内部,都有一个module
对象,表明当前模块。它有如下属性。
module.id
模块的识别符,一般是带有绝对路径的模块文件名。module.filename
模块的文件名,带有绝对路径。module.loaded
返回一个布尔值,表示模块是否已经完成加载。module.parent
返回一个对象,表示调用该模块的模块。module.children
返回一个数组,表示该模块要用到的其余模块。module.exports
表示模块对外输出的值。下面是一个示例文件,最后一行输出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' ] }
若是在命令行下调用某个模块,好比node something.js
,那么module.parent
就是undefined
。若是是在脚本之中调用,好比require('./something.js')
,那么module.parent
就是调用它的模块。利用这一点,能够判断当前模块是否为入口脚本。
if (!module.parent) { // ran with `node something.js` app.listen(8088, function() { console.log('app listening on port 8088'); }) } else { // used with `require('/.something.js')` module.exports = app; }
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'); });
为了方便,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
。
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(); }; });
Node使用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。
require
命令用于加载文件,后缀名默认为.js
。
var foo = require('foo'); // 等同于 var foo = require('foo.js');
根据参数的不一样格式,require
命令去不一样路径寻找模块文件。
(1)若是参数字符串以“/”开头,则表示加载的是一个位于绝对路径的模块文件。好比,require('/home/marco/foo.js')
将加载/home/marco/foo.js
。
(2)若是参数字符串以“./”开头,则表示加载的是一个位于相对路径(跟当前执行脚本的位置相比)的模块文件。好比,require('./circle')
将加载当前脚本同一目录的circle.js
。
(3)若是参数字符串不以“./“或”/“开头,则表示加载的是一个默认提供的核心模块(位于Node的系统安装目录中),或者一个位于各级node_modules目录的已安装模块(全局安装或局部安装)。
举例来讲,脚本/home/user/projects/foo.js
执行了require('bar.js')
命令,Node会依次搜索如下文件。
这样设计的目的是,使得不一样的模块能够将所依赖的模块本地化。
(4)若是参数字符串不以“./“或”/“开头,并且是一个路径,好比require('example-module/path/to/file')
,则将先找到example-module
的位置,而后再以它为参数,找到后续路径。
(5)若是指定的模块文件没有发现,Node会尝试为文件名添加.js
、.json
、.node
后,再去搜索。.js
件会以文本格式的JavaScript脚本文件解析,.json
文件会以JSON格式的文本文件解析,.node
文件会以编译后的二进制文件解析。
(6)若是想获得require
命令加载的确切文件名,使用require.resolve()
方法。
一般,咱们会把相关的文件会放在一个目录里面,便于组织。这时,最好为该目录设置一个入口文件,让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
文件。
第一次加载某个模块时,Node会缓存该模块。之后再加载该模块,就直接从缓存取出该模块的module.exports
属性。
require('./example.js'); require('./example.js').message = "hello"; require('./example.js').message // "hello"
上面代码中,连续三次使用require
命令,加载同一个模块。第二次加载的时候,为输出的对象添加了一个message
属性。可是第三次加载的时候,这个message属性依然存在,这就证实require
命令并无从新加载模块文件,而是输出了缓存。
若是想要屡次执行某个模块,可让该模块输出一个函数,而后每次require
这个模块的时候,从新执行一下输出的函数。
全部缓存的模块保存在require.cache
之中,若是想删除模块的缓存,能够像下面这样写。
// 删除指定模块的缓存 delete require.cache[moduleName]; // 删除全部模块的缓存 Object.keys(require.cache).forEach(function(key) { delete require.cache[key]; })
注意,缓存是根据绝对路径识别模块的,若是一样的模块名,可是保存在不一样的路径,require
命令仍是会从新加载该模块。
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
目录机制。
若是发生模块的循环加载,即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语句都不会执行了。
require
方法有一个main
属性,能够用来判断模块是直接执行,仍是被调用执行。
直接执行的时候(node module.js
),require.main
属性指向模块自己。
require.main === module // true
调用执行的时候(经过require
加载该脚本执行),上面的表达式返回false。
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
了。
require
命令是CommonJS规范之中,用来加载其余模块的命令。它其实不是一个全局命令,而是指向当前模块的module.require
命令,然后者又调用Node的内部命令Module._load
。
Module._load = function(request, parent, isMain) { // 1. 检查 Module._cache,是否缓存之中有指定模块 // 2. 若是缓存之中没有,就建立一个新的Module实例 // 3. 将它保存到缓存 // 4. 使用 module.load() 加载指定的模块文件, // 读取文件内容以后,使用 module.compile() 执行文件代码 // 5. 若是加载/解析过程报错,就从缓存删除该模块 // 6. 返回该模块的 module.exports };
上面的第4步,采用module.compile()
执行指定模块的脚本,逻辑以下。
Module.prototype._compile = function(content, filename) { // 1. 生成一个require函数,指向module.require // 2. 加载其余辅助方法到require // 3. 将文件内容放到一个函数之中,该函数可调用 require // 4. 执行该函数 };
上面的第1步和第2步,require
函数及其辅助方法主要以下。
require()
: 加载外部模块require.resolve()
:将模块名解析到一个绝对路径require.main
:指向主模块require.cache
:指向全部缓存的模块require.extensions
:根据文件的后缀名,调用不一样的执行函数一旦require
函数准备完毕,整个所要加载的脚本内容,就被放到一个新的函数之中,这样能够避免污染全局环境。该函数的参数包括require
、module
、exports
,以及其余一些参数。
(function (exports, require, module, __filename, __dirname) { // YOUR CODE INJECTED HERE! });
Module._compile
方法是同步执行的,因此Module._load
要等它执行完成,才会向用户返回module.exports
的值。