![](/img/trans.png)
[英]How do I test the code in a “if (require.main === module)” section of a Node.js script using Jest?
[英]Node.js, require.main === module
在Node.JS文档中,我发现了一句话说
当一个文件直接从 Node.js 运行时,
require.main
被设置到它的模块。 这意味着可以通过测试require.main === module
来确定文件是否已经直接运行。
我想问一下这里的main
是什么,我在源代码中找不到这个main
的定义,谁能帮忙,谢谢!
require
是一个函数。 .main
是该函数的属性,因此您可以引用require.main
。 您所指的那部分文档说您可以编写如下代码:
if (require.main === module) {
// this module was run directly from the command line as in node xxx.js
} else {
// this module was not run directly from the command line and probably loaded by something else
}
上面代码中的module
是传递给 node.js 加载的所有模块的变量,因此代码基本上说如果require.main
是当前模块,那么当前模块就是从命令行加载的模块。
设置该属性的代码在这里: https ://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/helpers.js#L44。
使用 Node.js 运行ECMAScript 模块时, require.main
不可用。 从 Node 13.9.0 开始,没有一种简洁的方法来确定模块是直接运行还是由另一个模块导入。 import.meta.main
值可能会允许将来进行此类检查(如果您认为这有意义,请评论模块问题)。
作为一种解决方法,可以通过将import.meta.url
值与process.argv[1]
进行比较来检查当前 ES 模块是否直接运行。 例如:
import { fileURLToPath } from 'url';
import process from 'process';
if (process.argv[1] === fileURLToPath(import.meta.url)) {
// The script was run directly.
}
这不处理在没有.js
扩展名的情况下调用脚本的情况(例如node script
而不是node script.js
)。 要处理这种情况,可以从import.meta.url
和process.argv[1]
中删除任何扩展名。
es-main
包(注意:我是作者)提供了一种方法来检查 ES 模块是否直接运行,考虑到它可以运行的不同方式(有或没有扩展)。
import esMain from 'es-main';
if (esMain(import.meta)) {
// The script was run directly.
}
我回答的很晚,但我把它留在这里供参考。
当文件是程序的入口点时,它就是主模块。 例如node index.js OR npm start
, index.js
是我们应用程序的主要模块和入口点。
但是我们可能需要将它作为一个模块运行,而不是作为一个主模块运行。 如果我们像这样require
index.js
,就会发生这种情况:
node -e "require('./index.js')(5,6)"
我们可以通过两种方式检查文件是否是主模块。
require.main === module
module.parent === null
假设我们有一个简单的index.js
文件,当它是主模块时它要么是console.log()
,要么当它不是主模块时它导出一个求和函数:
if(require.main === module) {
// it is the main entry point of the application
// do some stuff here
console.log('i m the entry point of the app')
} else{
// its not the entry point of the app, and it behaves as
// a module
module.exports = (num1, num2) => {
console.log('--sum is:',num1+num2)
}
}
检查上述情况的方法:
node index.js
--> 将打印im the entry point of the app
node -e "require('./index.js')(5,6)"
--> 将打印--sum is: 11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.