Node.js, require.main === 模块

标签 node.js

在Node.JS文档中,我找到一句话说

When a file is run directly from Node.js, require.main is set to its module. That means that it is possible to determine whether a file has been run directly by testing 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, require.main === 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45136831/

相关文章:

node.js - 分布式认证

javascript - 如何返回模板/html 页面并 promise 该页面上的函数返回值

javascript - Bluebird Promise 可以在 node.js 中与 redis 一起使用吗?

node.js - Heroku https ://www redirect to https://

javascript - 如何将时间戳添加到 package.json 中的脚本中?

node.js - 如何在没有客户端的情况下使用 Facebook 的 Passport 在 Node.js 中构建 REST 服务?

javascript - 使用 MEAN 堆栈查询关联模型

node.js - 使用 npm 和 CakePHP 3 - 文件位置

node.js - Firebird DB 连接错误

node.js - 如何使用 Mongoose 动态排序、改变字段和方向