发布于 2015-12-19 06:27:37 | 193 次阅读 | 评论: 0 | 来源: PHPERZ

这里有新鲜出炉的Node.js主要方法使用说明,程序狗速度看过来!

Node.js 服务器端的JavaScript

Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台, 用来方便地搭建快速的 易于扩展的网络应用· Node.js 借助事件驱动, 非阻塞I/O 模型变得轻量和高效, 非常适合 运行在分布式设备 的 数据密集型 的实时应用


Node.js中最常用的恐怕就是 require, exports 以及 module.exports 了,那么 exports 和 module.exports 这两者有什么区别,在什么情况下使用 exports,又在什么时候使用 module.exports。

先举个官网的例子:

// circle.js
var PI = Math.PI;

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

在 circle.js 中写的源字符串是上面贴出的代码,然而实际 Node.js 在加载的时候会在原字符串上外面拼出一个闭包,拼出之后的代码如下:

(function(exports, require, module, __dirname, __filename) {
    // circle.js
    var PI = Math.PI;
    
    exports.area = function (r) {
      return PI * r * r;
    };
    
    exports.circumference = function (r) {
      return 2 * PI * r;
    };
})

Node.js 调用这段代码的为:

function Module(id, parent) {
  this.id = id;
  this.exports = {};
  this.parent = parent;
  if (parent && parent.children) {
    parent.children.push(this);
  }

  this.filename = null;
  this.loaded = false;
  this.children = [];
}


Module.prototype._compile = function(content, filename) {
  var self = this;

  function require(path) {
    return self.require(path);
  }

  var dirname = path.dirname(filename);

  var args = [self.exports, require, self, filename, dirname];
  return compiledWrapper.apply(self.exports, args);
};

从上面这段代码可以看到 exports 是 module 的一个属性,exports 值为 {}。在拼接之后的代码中,给这个函数传入的 exports 是 module.exports, 也就是说 exports 和 modules.exports 引用的是同一个对象。如果我们给 exports 增加属性,那么因为 modules.exports 也会增加相同的属性,此时 modules.exports === exports。然而如果对 exports 赋值的话,那么就会造成 modules.exports 和 exports 不指向同一个对象,此时再对 exports 做任何动作都跟 modules.exports 没有任何关系了,用一段代码模拟就是:

var module = { exports: {}};
var exports = module.exports;
exports.a = 1;
console.log(module.exports); // {a: 1}

exports = {b:2};
console.log(module.exports); // {a: 1}

所以从上面的代码可以看出,如果我们想在模块文件中提供其他模块可以访问的接口,最好写成
exports["key"] = value 或者 module.exports = {key: value} 的形式, 总之别对 exports 赋值。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务