在Node.JS文档中,我发现了一句话
当文件直接从Node.js运行时,
require.main将设置为其模块.这意味着可以通过测试确定文件是否已直接运行require.main === module.
我想问一下main这里有什么,我main在源代码中找不到这个的定义,任何人都可以帮忙,谢谢!
jfr*_*d00 38
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
}
Run Code Online (Sandbox Code Playgroud)
module上面的代码是一个传递给node.js加载的所有模块的变量,所以代码基本上说if require.main是当前模块,那么当前模块是从命令行加载的.
设置该属性的代码如下:https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/helpers.js#L44.
Tim*_*aub 18
使用 Node.js运行ECMAScript 模块时,require.main不可用。从 Node 13.9.0 开始,没有一种简洁的方法来确定一个模块是直接运行还是由另一个模块导入。将来可能会有一个import.meta.main值允许进行这样的检查(如果您认为这有意义,请评论模块问题)。
作为一种解决方法,可以通过将import.meta.url值与进行比较来检查当前 ES 模块是否直接运行process.argv[1]。例如:
import { fileURLToPath } from 'url';
import process from 'process';
if (process.argv[1] === fileURLToPath(import.meta.url)) {
// The script was run directly.
}
Run Code Online (Sandbox Code Playgroud)
这不处理在没有.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.
}
Run Code Online (Sandbox Code Playgroud)
我回答得很晚,但我把它留在这里供参考。
\n当文件是程序的入口点时,它就是主模块。node index.js OR npm start, \xe2\x80\x8btheindex.js是我们应用程序的主模块和入口点。
但我们可能需要将其作为模块运行,而不是作为主模块。require如果我们喜欢 这样的话,就会发生这种情况 index.js :
node -e "require('./index.js')(5,6)"
我们可以通过两种方式检查一个文件是否是主模块。
\nrequire.main === modulemodule.parent === null假设我们有一个简单的index.js文件,console.log()当它是主模块时,它要么导出一个 sum 函数,当它不是主模块时:
if(require.main === module) {\n // it is the main entry point of the application\n // do some stuff here\n console.log('i m the entry point of the app')\n} else{\n // its not the entry point of the app, and it behaves as \n // a module\n module.exports = (num1, num2) => {\n console.log('--sum is:',num1+num2)\n }\n }\nRun Code Online (Sandbox Code Playgroud)\n检查上述情况的方法:
\nnode index.js--> 将打印i m the entry point of the appnode -e "require('./index.js')(5,6)"--> 将打印--sum is: 11| 归档时间: |
|
| 查看次数: |
7454 次 |
| 最近记录: |