你能解释我们为什么在节点中使用!module.parent吗?为什么Node.js访问父模块
if (!module.parent) {
app.listen(3000);
console.log('listening on port 3000');
}
Run Code Online (Sandbox Code Playgroud)
Dil*_*eni 13
我找到了答案.您可以使用module.parent来确定当前脚本是否由另一个脚本加载.示例在这里:
a.js:
if (!module.parent) {
console.log("I'm parent");
} else {
console.log("I'm child");
}
b.js:
require('./a')
run node a.js will output:
I'm parent
run node.b.js will output:
I'm child
Run Code Online (Sandbox Code Playgroud)