开发者

How to resolve a relative path in node?

Came across this situation recently - I have an environment variable for a directory path like so:

var fooDir = process.env.FOO_DIR;

and I want to make sur开发者_StackOverflow社区e this directory exists with a synchronous mkdir (at some point later):

fs.mkdirSync(fooDir, mode);

however if the user has supplied the environment variable via a realtive ~/ path node cannot resolve it

export FOO_DIR='~/foodir'

is there a way in node to resolve this without invoking a child process exec call to the actual shell? currently my solution is to do a replace myself like so:

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

just curious if someone has a better solution.


You have it right: ~ is expanded by the shell, not the OS, just like *. None of the C file functions that node.js wraps handle ~ either, and if you want this you have to do the replacement yourself, just as you've shown. I've done this myself in C when supporting config files that allow relative file paths.

However, you should probably handle the case where HOME isn't defined; I believe this happens with non-interaction logins with bash, for example, and the user could always choose to unset it.


You can convert it to absolute path with path.join:

const path = require('path')

const absolutePath = path.join(process.cwd(), relativePath)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜