path.join不起作用?

我想从一个path读取,我写了两个不同的代码。第一个代码不起作用,但第二个代码完美地工作。 我不明白差异。 有人可以向我解释发生了什么事吗? 谢谢。 该文件存储在/ modules / config /

第一编码:

var tmpModulePath = path.join('./modules/',"config/"); var moduleConfigInfo = require(tmpModulePath + "_test.js"); 

第二个代码:

 var tmpModulePath = path.join('./modules/',"config/"); var moduleConfigInfo = require("./" + tmpModulePath + "_test.js"); 

从第一个代码,我得到这个错误:无法find模块… _ tset.csv

如果你console.log生成的path,你会得到这个结果:

第一个代码块:

“模块/configuration/ _test.js”

第二个代码块:

“./modules/config/_test.js”

在第二种情况下,您有一个从当前目录( ./ )开始的相对path。 require将从当前目录开始寻找模块文件夹。

在第一种情况下,path是绝对path,这意味着require将从文件系统的根path开始查找modules文件夹。

我希望你现在明白这个差别。

你真正想在这种情况下使用的是path.resolve

 var tmpModulePath1 = path.resolve('./', 'modules/',"config/", 'test.js'); 

检查这个问题的答案,了解.join.resolve之间的区别。