简体   繁体   English

如何解析节点中的相对路径?

[英]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 sure this directory exists with a synchronous mkdir (at some point later):我想确保这个目录与同步 mkdir 存在(稍后):

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?节点中有没有办法解决这个问题,而无需调用实际 shell 的子进程 exec 调用? 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 *.你说得对: ~ 由shell扩展,而不是操作系统,就像 *. 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. node.js 包装的 C 文件中的任何一个都不能处理 ~ 或者,如果你想要这个,你必须自己做替换,就像你展示的那样。 I've done this myself in C when supporting config files that allow relative file paths.当支持允许相对文件路径的配置文件时,我自己在 C 中完成了此操作。

However, you should probably handle the case where HOME isn't defined;但是,您可能应该处理未定义 HOME 的情况; I believe this happens with non-interaction logins with bash, for example, and the user could always choose to unset it.我相信这发生在使用 bash 的非交互登录中,例如,用户可以随时选择取消设置。

Check out Rekuire , it is a node module that solves the relative paths problem in NodeJs.查看Rekuire ,它是一个解决 NodeJs 中相对路径问题的节点模块。

You can convert it to absolute path with path.join :您可以使用path.join将其转换为绝对路径:

const path = require('path')

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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