NodeJS 中 'if (!module.parent)' 是什么意思?
在 NodeJS 应用程序中你经常看到类似这样的代码
module_parent_example.js
if (!module.parent) {
app.listen(3000);
}这意味着:仅当你正在运行该文件时才运行 app.listen(3000)
假设此代码在 index.js 中。在这种情况下,仅当你直接运行 index.js(即使用 node index.js)时代码才会执行,而不会在 index.js 从另一个文件 require 时执行(通过 require('./index.js');)。
如果 index.js 从另一个 Javascript 模块(即文件)被 require,module.parent 将被设置为该模块。
Check out similar posts by category:
Javascript, NodeJS
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow