Node.js 是什么?
Node.js® is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
Current Version: v0.10.33
为什么要有 Node 模块?
模块,是 Node 让代码易于重用的一种组织和包装方式
模块创建流程
创建模块
var a = 'a';
function A() {
console.log(a);
}
exports.printA = A;
引入模块
var a = require('./module_');
a.printA();
模块暴露构造函数
//定义
var B = function (input) {
this.input = input;
}
B.prototype.printB = function () {
console.log(this.input);
}
module.exports = exports = B;
//调用
var B = require('./module_');
var b = new B('asdf');
b.printB();
- exports
只是对 module.exports 的一个全局引用,最初被定义为一个可以添加属性的空对象 - exports.printA
是 module.exports.printA 的简写 - exports = B
将会打破 module.exports 和 exports 之间的引用关系 - module.exports = exports
可以修复链接
Monkey Patching
Node 将模块作为对象缓存起来
第一个文件会将模块返回的数据存到程序的内存中,第二个文件就不用再去访问和计算模块的源文件了
并且第二次引入有机会修改缓存的数据
欢迎直接访问我的个人博客,阅读效果更佳:https://yuzhouwan.com/posts/23363/