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

查看:21
本文介绍了我可以知道,在 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天全站免登陆