在我的模块中,我需要检测何时从命令行或从另一个模块调用它。
const isFromCLI = '????'
我使用的是Babel/ ES6,所以当从命令行调用时,index.js
被调用(使用babel代码),这将传递给script.js
(使用ES6代码)。因此,从脚本文件中,module.parent
返回module
( index.js
文件)。所以我不能用 module.parent
!
此外,当从命令行或从另一个模块调用时,module.main
是undefined
(在script.js
中)。所以我不能用 module.main
!
这是其他人提出的两种解决方案,但它们对我不起作用。
在使用Babel/ES6.时,是否有简单的检测方法?
更新
当从命令行或从另一个模块调用时,require.main
返回module
。
发布于 2017-03-10 14:24:33
发布于 2017-03-10 14:45:51
您可以使用节点环境变量。
您可以设置如下环境变量:
CLI=true node app.js
然后得到这样的环境变量:
const isFromCLI = process.env.CLI === 'true'
注意: process.env.CLI
将是一个字符串。
更新:
如果要执行类似node app.js --cli
的操作,可以执行以下操作:
let isFromCLI
process.argv.forEach(function (val, index, array) {
if (array[index] === '--cli') {
isFromCLI = true
}
})
console.log(isFromCLI)
https://stackoverflow.com/questions/42720323
复制相似问题