javascript - 如果我们将目录位置传递给 Node.js require 函数会发生什么?

标签 javascript node.js express

我已经克隆了 Express.js repo包含一个具有 Express.js 不同用例的示例文件夹。我打开了 Hello World 示例,代码以以下行开头

var express = require('../../');

我理解该文件中的其余代码,但上面的行让我难以理解?我知道 require 函数用于在您的项目中包含一个 JS 模块,并且应该将模块名称作为参数传递给 require() 函数,但是在这种情况下上面的语句,我们传入的是一个目录,它要做什么?

最佳答案

您正在传递位于当前文件夹后两个文件夹的 index.js 文件。

例子:

enter image description here

所以,如果您的 yourFile.js

上有这个
var something = require('../../');

您正在引用您的 index.js

如果你这样做是完全一样的:

var something = require('../../index');

两者都与这个完全相同(使用.js,在这种情况下是不必要的)

var something = require('../../index.js');

发生这种情况是因为 index.js 是默认名称。

您可以阅读更多 at nodejs.org但这里引用了重要的部分:

If there is no package.json file present in the directory, then Node.js will attempt to load an index.js or index.node file out of that directory. For example, if there was no package.json file in the above example, then require('./some-library') would attempt to load:

./some-library/index.js

./some-library/index.node

关于javascript - 如果我们将目录位置传递给 Node.js require 函数会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32767387/

相关文章:

express - 在Redis中存储JWT token 的标准做法是什么?

javascript - 仅当浏览器高度小于页面时,如何使用 jquery 显示 "back to top"按钮?

JavaScript 堆内存不足增加 Node 内存或优化我的代码

javascript - 将 HTML 剥离为允许的标签

javascript - 具有对象文字自引用的 ES6 代理拦截器

javascript - Node/Express/Request - 尝试使用参数代理 POST 请求会抛出 "Write after end"

javascript - 如何按值过滤 `objects`

javascript - 如何释放网页上的系统资源/CPU使用率?

javascript - c3.js如何在x/y轴上设置json数据

javascript - Multer 只读未定义