nodeJs学习笔记二

modules 模块

Node 使用 CommonJS 模块系统.

var a = require('./b');
var helloWorld = 'helloWorld';
a.add(1,1);//2
//b.js
exports.add = function(x , y){
return x + y;
}
exports.hello = function(){
console.log(helloWorld);
}

require('./b') 引用当前目录下的b.js

exports.add = function(){} 导出一个函数,这样require的时候就可以调用该函数了.可以导出多个函数

var helloWorld 这个变量是个私有的 外部是访问不到的 只有在这个文件下使用 如果想让到外部使用就得 exports.helloWorld = helloWorld;

核心模块

使用 require() 时,核心模块总是优先加载。例如,require('http') 总是返回内置的 HTTP 模块,即使该名称的文件存在。

文件模块

如果require 没有找到确切文件 node会尝试给文件名后缀加 .js来查找,如果还没有会加.node 用dlopen 来加载

require('/') 会根据绝对路径去查找

require('./') 会根据相对路径去查找

require('mod') 会去node核心模块去查找 位置在node_modules/ 下

如果还是没找到 node会从node_modules 上一级去查找 以此类推 直到根目录为止

首先,/node_modules 不会附加到一个以 /node_modules 结尾的文件夹后面。

其次,如果调用 require() 的文件已经在一个 node_modules 层级里,那么最顶层的 node_modules 文件夹将被视为搜索树的根。