如何检测脚本是否直接从节点控制台执行
How to detect if a script is executed directly from the node console
是否可以使用node.js控制台判断当前脚本是否从执行
:
$ node
> require('./script');
或来自运行 的经典方式使用文件,例如:
node script.js
您可以查看 module.parent !== null
。如果是这样,那么该文件是从其他脚本 require()
d 生成的。如果该语句为假,则它是最初从命令行加载的脚本。
如果您想具体了解父级是否是 repl,可以查看 module.parent && module.parent.id === 'repl'
。
module.parent
已记录 here。
是否可以使用node.js控制台判断当前脚本是否从执行
:$ node
> require('./script');
或来自运行 的经典方式使用文件,例如:
node script.js
您可以查看 module.parent !== null
。如果是这样,那么该文件是从其他脚本 require()
d 生成的。如果该语句为假,则它是最初从命令行加载的脚本。
如果您想具体了解父级是否是 repl,可以查看 module.parent && module.parent.id === 'repl'
。
module.parent
已记录 here。