如何检测我的 node .使用SH:node path-to-file或JS:require('path-to-file')调用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://nodejs.org/docs/latest/api/modules.html#modules_accessing_the_main_module

Node.js相关问答推荐

在child_Process中持久运行SSH命令

使用prisma迁移到SQL失败

monorepo内的NPM包使用不在注册表中的本地包

错误:找不到模块';/var/apps/前端/bash';

Twilio-获取呼叫录音不起作用的请求

如何在Angular jest测试中调用Nodejs的垃圾收集? node v20的测试速度慢且内存泄漏

合并Shift对象数组以创建最终的排班表

在对象数组中的数组中嵌套 $lookup - Mongodb

如何防止 Chrome 通过 Selenium 崩溃?

登录用户并获取他们的个人资料

TypeError:在使用 Jest、Supertest、Express、Typescript 进行测试时无法读取未定义的属性(读取listen)

在快速路由中使用 axios 会在数据字段中返回特殊字符而不是 json

如何为单个 mongo nodejs 驱动程序找到最佳连接池大小

如何使用来自前一阶段的另一个数组的聚合mongoose 在数组中添加字段

使用 .pipe(res) 向客户端发送音频不允许您搜索?

如何让我的 Next.js 应用在运行 ubuntu-latest 的 Azure 应用服务中启动?

这到底是什么';拒绝未经授权';对我来说是什么意思?

Node.js 支持 =>(箭头函数)

npm WARN 不推荐使用 graceful-fs@3.0.8:graceful-fs 版本 3

npm install packagename --save-dev 不更新 package.json