NodeJs Require机制
写NodeJS程序的时候,经常需要写require,但是对于require的原理又不是很了解,去看了一下官方文档,这里做下笔记以免遗忘!
require(X) from module at path Y 1. If X is a core module, a. return the core module b. STOP 2. If X begins with './' or '/' or '../' a. LOAD_AS_FILE(Y + X) b. LOAD_AS_DIRECTORY(Y + X) 3. LOAD_NODE_MODULES(X, dirname(Y)) 4. THROW "not found" LOAD_AS_FILE(X) 1. If X is a file, load X as JavaScript text. STOP 2. If X.js is a file, load X.js as JavaScript text. STOP 3. If X.json is a file, parse X.json to a JavaScript Object. STOP 4. If X.node is a file, load X.node as binary addon. STOP LOAD_AS_DIRECTORY(X) 1. If X/package.json is a file, a. Parse X/package.json, and look for "main" field. b. let M = X + (json main field) c. LOAD_AS_FILE(M) 2. If X/index.js is a file, load X/index.js as JavaScript text. STOP 3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP 4. If X/index.node is a file, load X/index.node as binary addon. STOP LOAD_NODE_MODULES(X, START) 1. let DIRS=NODE_MODULES_PATHS(START) 2. for each DIR in DIRS: a. LOAD_AS_FILE(DIR/X) b. LOAD_AS_DIRECTORY(DIR/X) NODE_MODULES_PATHS(START) 1. let PARTS = path split(START) 2. let I = count of PARTS - 1 3. let DIRS = [] 4. while I >= 0, a. if PARTS[I] = "node_modules" CONTINUE b. DIR = path join(PARTS[0 .. I] + "node_modules") c. DIRS = DIRS + DIR d. let I = I - 1 5. return DIRS
总结一下伪代码就是:
一般我们在nodjejs中require的时候通常有三种写法。
1) require('内置module') -> 直接返回core module
2) require('./或者../这种带有路径的') -->先查找有没有这个文件,没有然后当作文件夹来查找
3) require('包名比如jquery这种的的') --> 去当前目录同级的node_modules目录下查找,拿jquery举例,先查找node_modules/jquery.js是否存在,不存在则查找node_modules/jquery目录是否存在,如果存在,那么查找node_modules/jquery/package.json中的main字段指向,然后找到相应的js文件然后进行加载。