检测是通过require调用还是通过命令行直接调用 [英] Detect if called through require or directly by command line

查看:77
本文介绍了检测是通过require调用还是通过命令行直接调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测使用SH:node path-to-file还是JS:require('path-to-file')调用了Node.JS文件?

How can I detect whether my Node.JS file was called using SH:node path-to-file or JS:require('path-to-file')?

这是相当于我在Perl中上一个问题的Node.JS:

This is the Node.JS equivalent to my previous question in Perl: How can I run my Perl script only if it wasn't loaded with require?

推荐答案

if (require.main === module) {
    console.log('called directly');
} else {
    console.log('required as a module');
}

请参阅此处的文档: https://nodereferrer> https://nodejs.org/docs/Latest/api/modules.html#modules_accessing_the_main_module

这篇关于检测是通过require调用还是通过命令行直接调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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