我可以知道,在node.js,如果我的脚本是直接运行或由另一个脚本加载?
我刚刚开始使用node.js,我有一些Python的经验。 在Python中,我可以检查__name__variables是否设置为"__main__" ,如果是,我会知道我的脚本正在直接运行。 在这种情况下,我可以运行testing代码或直接以其他方式使用模块。
在node.js中有类似的东西吗?
您可以使用module.parent来确定当前脚本是否由另一个脚本加载。
例如
a.js :
if (!module.parent) { console.log("I'm parent"); } else { console.log("I'm child"); }
b.js :
require('./a')
运行node a.js将输出:
I'm parent
运行node.b.js会输出:
I'm child
接受的答案是好的。 我从官方文档中join这个完整性:
访问主模块
当一个文件直接从Node运行时, require.main被设置为它的module 。 这意味着您可以确定文件是否已经通过testing直接运行
require.main === module
对于文件"foo.js" ,如果通过node foo.js运行, node foo.js false如果由require('./foo')运行node foo.js false 。
由于module提供了一个filename属性(通常相当于__filename ),因此可以通过检查require.main.filename来获取当前应用程序的入口点。
这两个选项!module.parent和require.main === module工作。 如果您对更多的细节感兴趣,请阅读我关于此主题的详细博客文章 。