我想检查我的模块是否被包含或直接运行。我如何在node.js中做到这一点?
当前回答
文档描述了另一种可能是首选的方法:
当一个文件直接从Node运行时,require。Main被设置为它的模块。
为了利用这一点,检查这个模块是否是主模块,如果是,调用你的主代码:
function myMain() {
// main code
}
if (require.main === module) {
myMain();
}
编辑:如果你在浏览器中使用这段代码,你会得到一个“引用错误”,因为“要求”没有定义。为了防止这种情况,可以使用:
if (typeof require !== 'undefined' && require.main === module) {
myMain();
}
其他回答
if (!module.parent) {
// this is the main module
} else {
// we were require()d from somewhere else
}
编辑:如果你在浏览器中使用这段代码,你会得到一个“引用错误”,因为“模块”没有定义。为了防止这种情况,可以使用:
if (typeof module !== 'undefined' && !module.parent) {
// this is the main module
} else {
// we were require()d from somewhere else or from a browser
}
文档描述了另一种可能是首选的方法:
当一个文件直接从Node运行时,require。Main被设置为它的模块。
为了利用这一点,检查这个模块是否是主模块,如果是,调用你的主代码:
function myMain() {
// main code
}
if (require.main === module) {
myMain();
}
编辑:如果你在浏览器中使用这段代码,你会得到一个“引用错误”,因为“要求”没有定义。为了防止这种情况,可以使用:
if (typeof require !== 'undefined' && require.main === module) {
myMain();
}
推荐文章
- ReferenceError: description没有定义NodeJs
- 将一个二进制的NodeJS Buffer转换为JavaScript的ArrayBuffer
- AngularJS只适用于单页应用程序吗?
- 如何在vue-cli项目中更改端口号
- 同步和异步编程(在node.js中)的区别是什么?
- 如何编辑通过npm安装的节点模块?
- “node_modules”文件夹应该包含在git存储库中吗
- 使用package.json在全局和本地安装依赖项
- this.libOptions.parse不是一个函数
- 对嵌套文件夹运行npm install的最好方法是什么?
- 节点Multer异常字段
- 很好的初学者教程socket.io?
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在Ubuntu上安装Node.js
- 使用express.js代理