javascript - 检测 ES 模块是否从 Node 中的命令行运行

标签 javascript node.js node-modules es6-modules

在 Node 中使用 CommonJS 模块时,您可以使用 require.main === module 检测脚本是否正在从命令行运行。

在 Node 中使用 ES 模块(使用 --experimental-modules 标志)时,检测脚本是否正在从命令行运行的等效方法是什么?

最佳答案

使用

if (import.meta.url === `file://${process.argv[1]}`) {
  // module was not imported but called directly
}

参见 MDN docs on import.meta了解详情。

2021 年 9 月 27 日更新

也许更健壮,但涉及一个 extra import (通过 Rich Harris )

import {pathToFileURL} from 'url'

if (import.meta.url === pathToFileURL(process.argv[1]).href) {
  // module was not imported but called directly
}

关于javascript - 检测 ES 模块是否从 Node 中的命令行运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57838022/

相关文章:

node.js - NPM 模块不会在没有 sudo 的情况下全局安装

node.js - 错误: DPI-1047: Cannot locate a 64-bit Oracle Client library in NodeJS

node.js - 使用 Node-Schedule 开始 BotBuilder 对话

javascript - jQuery ajax 无法检索 json

javascript - 为什么使用 ng-value ="true"和值 ="1"选择两个单选按钮

javascript - Couchdb、couch-connector 和多个数据库

node.js - 列出文件时,node.js 出现类型错误

node.js - SequelizeJs : order by term

javascript - 制作一个接受或不接受参数的 Node.js 模块,并返回适当的函数/对象

javascript - 保持悬停状态直到类被交换