node.js笔记

模块

  1. 一个js文件就可以是一个模块,每个模块中有独立的作用域。而被调用的时候node.js会把该模块包装成一个匿名函数,每个模块中的公共变量会变成当前匿名函数中的局部变量。
  2. 但是如果想对外暴露模块中的变量(如函数)

    • 用法
      模块hello.js

      1
      2
      3
      4
      hi(name){
      console.log('hello '+ name );
      }
      module.exports=hi; // 对外暴露函数变量

      调用模块的外部环境

      1
      2
      var hello=require('./hello'); //模块作为变量保存在当前作用域,相对路径
      hi(chellh); //调用模块中暴露的变量
    • exports和module.exports
      node.js为每个模块都会准备一个modules对象,

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      var module = {
      id: 'hello', //模块名
      exports: {}
      };
      var load = function (module) {
      // hello.js的文件内容
      ...
      // load函数返回:
      return module.exports;
      };
      var exported = load(module.exports, module);
      save(module, exported);

      当我们暴露函数变量的时候module.exports=hi;,函数变量hi实际是module对象中的exports的一个值,module再作为参数传递给函数load,即真正作用的是module对象。

      1
      2
      exports.foo = function () { return 'foo'; };
      module.exports.foo = function () { return 'foo'; };

      其中,exports是指向module.exports的一个引用。exports 和 module.exports是指向同一块内存块,如果直接给exports赋值,则会改变exports的指向,而不会影响到module.exports,但传递给load函数的是modul对象。

      1
      2
      module.exports = function () { return 'foo'; }; //正确
      exports = function () { return 'foo'; }; //错误,改变exports的指向

Event Loop

看这里js的单线程和异步