Node.js module mechanism adopted Commonjs norms, to make up for the current application is not standard JavaScript development of large defects, similar to the Java class files, import mechanism in Python, Node.js can be derived by module.exports, require and the introduction of a module.
In the loading mechanism module, Node.js uses a strategy of delay in loading, used only in the case of system modules will be loaded after loading is complete it will put binding_cache in.
Interview Guide
require的加载机制?
Reference: module loading mechanismmodule.exports与exports的区别
Reference: Object reference relationship between the study假设有a.js、b.js两个模块相互引用,会有什么问题?是否为陷入死循环?
, The reference text "Circular references Module 1"a模块中的undeclaredVariable变量在b.js中是否会被打印?
, The reference text "Circular references Module 2"模块在require的过程中是同步还是异步?
Reference text module loading mechanism "File Module"
Classification Module
System Module
C / C ++ module, also known as built-in built-in modules, generally used for native module called out in require
Built-in modules (C / C ++) native module, used in the development of Node.js http, buffer, fs, etc., are also called bottom.
Third party modules
Non-called third-party modules Node.js own module, in fact divided file path in the module (in .
, ..
, /
beginning) and custom module (such as express, koa frame, moment.js etc.)
javaScript module: e.g.
hello.js
json module: e.g.
hello.json
C / C ++ modules: After compiling extension module named .node, for example,
hello.node
Directory Structure
Some Node.js ├── benchmark performance test code ├── deps Node.js rely ├── doc document ├── lib Node.js Foreign exposed js module source code ├── src Node.js of c / c ++ source file , built-in modules ├── test unit testing tool ├── tools used when compiling ├── doc api documentation ├── vcbuild.bat win platform makefile file ├── node.gyp node-gyp build compilation task configuration file ...
Module loading mechanism
面试中可能会问到能说下require的加载机制吗?
Usually the modules are loaded in Node.js undergoes three steps, 路径分析
, 文件定位
, 编译执行
.
According to the classification module performs the following sequence of priority loading:
System Cache : module will be executed after the cache, the first cache is first loaded, determines whether the value of the cache.
System modules : i.e. primary module, the priority after the cache loading, part of the core module has been compiled into a binary omitted
路径分析
,文件定位
applied directly to aFile module : priority loading
.
,..
,/
beginning, if there is no file with the extension, in turn follow.js
,.json
,.node
were trying to make up the extension, it is in the process of trying also to synchronous blocking mode to determine the file exists , optimize performance from angle to look at.json
,.node
should add the file extension.Directory as a module : This occurs when the file module loading process, but could not find, but found to be the case of a directory, this time as a directory will
包
be handled, Node uses Commonjs this specification, the first will Find package.json file in the root directory of the project, main properties defined in the file out of("main":"lib/hello.js")
the entrance to load the file description, nor is loaded into, it will throw default error: error: Can not find module ' lib / hello.js'node_modules directory to load : For a system module, the module can not find the path to the file, Node.js is looked up from the parent directory of the current module, until the root system
FIG require timing module loading
Where the cache module
The above explained the loading mechanism module, the module mentioned in the middle after the initial load will be cached, there is no doubt that the cache module where?
Providing Node.js require.cache API module cached view, the return value is an object, in order to verify, here to make a simple test, as follows:
New test-module.js file
Here I export a variable and a method
module.exports={
a : 1,
test : () => { }
}
New test.js file
require('./test-module.js');
console.log(require.cache);
Load test-module.js file in this file, require.cache after printing inside look at what is returned? See the following results should be very clear, module names, addresses, export the data are very clear.
Module circular reference
Question 1
Suppose there a.js, b.js two modules refer to each other, what's the problem? Whether it is an endless loop? Look at the following example
// a.js
console.log('a模块start');
exports.test = 1;
undeclaredVariable = 'a模块未声明变量'
const b = require('./b');
console.log('a模块加载完毕: b.test值:',b.test);
// b.js
console.log('b模块start');
exports.test = 2;
const a = require('./a');
console.log('undeclaredVariable: ', undeclaredVariable);
console.log('b模块加载完毕: a.test值:', a.test);
Question 2
Whether a module undeclaredVariable variable will be printed in b.js in?
Console node a.js
view the results:
a模块start
b模块start
undeclaredVariable: a模块未声明变量
b模块加载完毕: a.test值: 1
a模块加载完毕: b.test值: 2
Question 1, start a.js
time, will be loaded b.js
, then b.js
he also loaded a.js
, but this time a.js
the module has not been executed, returns a a.js
module exports
object is 未完成的副本
given to the b.js
module (and therefore would not be caught dead cycle). Then b.js
, after the completion of loading the exports
object is supplied to the a.js
module
Question 2, as undeclaredVariable
is an undeclared variable, which is linked to a global variable, then in other places, of course you can get.
Before execution of the code, using a code will Node.js encapsulating wrapper, as shown in the following example:
(function(exports, require, module, __filename, __dirname) {
// 模块的代码
});
Object reference relationship between the study
Perhaps interview examine the most problems: the difference module.exports and exports?
Shortcut exports equivalent module.exports follows:
const exports = modules.exports;
But be careful not to change the point of exports, we can exports.test='a'
be exported to an object like this, but can not be directly assigned to the following examples, it will change the point of exports
// 错误的写法 将会得到 undefined
exports = {
'a': 1,
'b': 2
}
// 正确的写法
modules.exports = {
'a': 1,
'b': 2
}
A better understanding of the relationship between, can refer to an object in JavaScript references https://www.nodejs.red/#/javascript/object ?
Article Source
Reprinted from Nodejs technology stack