How to resolve relative path in node?

Most recently, a situation occurred: I have an environment variable for the directory path:

var fooDir = process.env.FOO_DIR; 

and I want to make sure that this directory exists with synchronous mkdir (at some point later):

 fs.mkdirSync(fooDir, mode); 

however, if the user has provided an environment variable through realtive ~ / path node cannot solve it

 export FOO_DIR='~/foodir' 

Is there a way in node to resolve this without calling the exec call for the child process in a valid shell? currently my solution is to replace myself like this:

 fooDir = fooDir.replace(/^~\//, process.env.HOME + '/'); 

just wondering if anyone has a better solution.

+4
source share
2 answers

You have this right: ~ expands by the shell, not the OS, like *. None of the functions of the C file that node.js wraps the ~ handle, and if you want it, you need to do the replacement yourself, as you showed. I did this myself in C, supporting configuration files that allow relative file paths.

However, you should probably handle the case where the HOME is not defined; I believe this happens, for example, with inputs without interacting with bash, and the user could always disable it.

+4
source

Check out Rekuire , this is a node module that solves the relative path problem in NodeJs.

0
source

All Articles