We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
来自于:Nodejs 官方文档
考虑这种情形:如果 a.js 文件 require 了 b.js,而 b.js 又 require 了 a.js,那么会造成死循环吗?
a.js
b.js
官方文档举了这个例子:
console.log('a starting'); exports.done = false; const b = require('./b.js'); console.log('in a, b.done = %j', b.done); exports.done = true; console.log('a done');
console.log('b starting'); exports.done = false; const a = require('./a.js'); console.log('in b, a.done = %j', a.done); exports.done = true; console.log('b done');
console.log('main starting'); const a = require('./a.js'); const b = require('./b.js'); console.log('in main, a.done=%j, b.done=%j', a.done, b.done);
执行 node main.js 会输出什么结果?
node main.js
main.js
main starting
a starting
done
b starting
注意,这个时候就形成了循环,而 node 为了防止出现死循环,在这个地方只会把 a.js 未加载完的副本 exports 的对象返回给 b.js
In order to prevent an infinite loop, an unfinished copy of the a.js exports object is returned to the b.js module.
因为执行到现在,a.js 只加载到了第三行,而只在第二行 exports 了一个值为 false 的 done,所以此时 b.js require 到的 a.js 的 done 值为 false,输出 in b, a.done = false
in b, a.done = false
b done
'in a, b.done = true
a done
综上,输出顺序为
in a, b.done = true
in main, a.done=true, b.done=true
The text was updated successfully, but these errors were encountered:
No branches or pull requests
来自于:Nodejs 官方文档
考虑这种情形:如果
a.js
文件 require 了b.js
,而b.js
又 require 了a.js
,那么会造成死循环吗?官方文档举了这个例子:
a.js
b.js
main.js
执行顺序
执行
node main.js
会输出什么结果?main.js
是入口文件,当程序执行main.js
的时候,首先会打出main starting
,然后加载a.js
a.js
首先输出a starting
,接着把done
变量 exports 出去,此时done
为 false,然后加载b.js
b.js
首先输出b starting
,接着把done
变量 exports 出去,此时done
为 false,然后加载a.js
注意,这个时候就形成了循环,而 node 为了防止出现死循环,在这个地方只会把
a.js
未加载完的副本 exports 的对象返回给b.js
因为执行到现在,
a.js
只加载到了第三行,而只在第二行 exports 了一个值为 false 的done
,所以此时b.js
require 到的a.js
的done
值为 false,输出in b, a.done = false
b.js
加载完,exports 的done
置为 true,并输出b done
;a.js
,因为 b.js 加载完后已经把done
置为 true了,所以接着输出'in a, b.done = true
,然后把 exports 的
done
置为 true,并输出a done
;main.js
,继续加载b.js
,因为之前已经加载过b.js
了,所以只会取缓存中的结果,此时a.js
和b.js
都已经加载完毕了,且 done 值都为 true。综上,输出顺序为
main starting
a starting
b starting
in b, a.done = false
b done
in a, b.done = true
a done
in main, a.done=true, b.done=true
The text was updated successfully, but these errors were encountered: