我可以在node.js中知道我的脚本是直接运行还是由另一个脚本加载吗? [英] Can I know, in node.js, if my script is being run directly or being loaded by another script?

查看:96
本文介绍了我可以在node.js中知道我的脚本是直接运行还是由另一个脚本加载吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用node.js,并且对Python有一定的经验.在Python中,我可以检查__name__变量是否设置为"__main__",如果是的话,我会知道我的脚本正在直接运行.在那种情况下,我可以运行测试代码或以其他方式直接使用该模块.

I'm just getting started with node.js and I have some experience with Python. In Python I could check whether the __name__ variable was set to "__main__", and if it was I'd know that my script was being run directly. In that case I could run test code or make use of the module directly in other ways.

node.js中有类似的东西吗?

Is there anything similar in node.js?

推荐答案

您可以使用module.parent确定当前脚本是否由另一个脚本加载.

You can use module.parent to determine if the current script is loaded by another script.

例如

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

这篇关于我可以在node.js中知道我的脚本是直接运行还是由另一个脚本加载吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆