我已经克隆了 Express.js repo包含一个具有 Express.js 不同用例的示例文件夹。我打开了 Hello World 示例,代码以以下行开头
var express = require('../../');
我理解该文件中的其余代码,但上面的行让我难以理解?我知道 require
函数用于在您的项目中包含一个 JS 模块,并且应该将模块名称作为参数传递给 require()
函数,但是在这种情况下上面的语句,我们传入的是一个目录,它要做什么?
最佳答案
您正在传递位于当前文件夹后两个文件夹的 index.js
文件。
例子:
所以,如果您的 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/