引用Modules时Node.js的搜寻规则

来源:互联网 发布:家有n多宝贝 淘宝 编辑:程序博客网 时间:2024/04/30 01:42

1、若请求的是内置模块如http、fs等,Node直接使用,无需搜寻

2、如果请求的模块名称前包含路径参数如表示当前运行的.js文件所在的目录./或上一级目录../等,Node会到指定目录查找模块并尝试加载。如果未指定模块的扩展名.js,Node首先会查找匹配该名字的文件夹,如果未找到该文件夹,Node会自动为模块名加上.js,.json,.node并尝试依次加载指定类型的模块(以.node结尾的模块会被编译为附加模块)

3、若请求的模块并未指定路径,Node首先会在当前路径下的node_modules/子文件夹下查找指定模块,若存在则加载,否则Node会在当前位置的路径树中查找node_modules/文件夹,若查找失败Node会到一些标准的默认位置继续查找,如/usr/lib或者/usr/local/lib

4、如果Node仍搜寻失败,则抛错


在《Learning Node 2nd》中原文如下:

Searching for Modules
Node.js uses a pretty straightforward set of rules for finding modules requested with the require function:

1. If the requested module is a built-in one—such as http or fs—Node uses that.

2. If the module name in the require function begins with a path component— ./ , ../ , or / — Node looks in the specified directory for that module and tries to load it there. If you don’t specify a .js extension on your module name, Node first looks for a folder-based
module of that name. If it does not find that, it then adds the extensions .js, .json, .node,and in turn tries to load modules of those types. (Modules with the extension .node are compiled add-on modules.)
3. If the module name does not have a path component at the beginning, Node looks in the node_modules / subfolder of the current folder for the module there. If it is found,that is loaded; otherwise, Node works its way up the path tree of the current location
looking for node_modules/ folders there. If those continue to fail, it looks in some standard default locations, such as /usr/lib or /usr/local/lib.
4. If the module isn’t found in any of these locations, an error is thrown.

联想到C语言中使用include包含头文件时使用<>和""的区别,使用<>则C编译器会到编译器的类库路径里面搜寻头文件,而使用""C编译器会首先到程序目录的相对路径搜寻,一般用于自己写的或者引用他人写的共享的头文件,若在相对路径搜寻不到,C编译器会到编译器的类库路径里搜寻,若仍搜寻不到,则同样回报错。

个人觉得C语言的头文件和Node.js中的module是一个意思,可以说都是库文件,不同的是引用方法和搜寻规则,Node.js中通过require('Module')函数实现引用,并不像C编译器中区分#include <.h>和#include ".h"。

区别于很多非Node.js系统,Node.js并不会把模块、引用部件或动态库集中存储在一个中央位置,当需要请求很多包而这些包本身又需要调用不同版本的模块时这种存储方式就会相当麻烦,在Node中,可以任意包含不同版本的模块,Node的命名空间和模块规则决定了这样的调用根本不会引起冲突。而且为了满足项目的需求可以对项目所引用的个别模块和部件进行升级或更改操作,而这些操作并不会影响到Node 模块系统的其它模块。


在《Learning Node 2nd》中原文如下:

This is one of the most powerful and awesome features of the Node.js module system! In so many
other systems, modules, widgets, or dynamic libraries are all stored in a central location, which
creates versioning nightmares when you require packages that themselves require different
versions of some other module. In Node, they are free to include these different versions of the
other modules, and Node’s namespace and module rules mean that they do not interfere with
each other at all! Individual modules and portions of a project are free to include, update, or
modify included modules as they see fit without affecting the rest of the system.

0 0