简体   繁体   中英

path.join does not work?

I want to read from a path and I wrote two different codes.The first code does not work but the second code works perfectly. I do not understand the differences. can someone explain to me what is going on? thanks. the file is stored in /modules/config/

First Code:

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

Second code:

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

from the first code, I do get this error: Can not find module ..._tset.csv

If you console.log the generated path you get this results:

First code block:

"modules/config/_test.js"

Second code block:

"./modules/config/_test.js"

In the second case, you have a relative path starting from your current directory ( ./ ). require will look for a modules folder starting from your current directory.

In the first case, the path is absolute, meaning that require will look for a modules folder starting from the root path of your filesystem.

I hope you understand the difference now.

What you really want to use in this case is path.resolve :

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

Check the answer to this question to understand the difference between .join and .resolve .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM