Expanding / Resolving ~ in node.js

前端 未结 7 1725
慢半拍i
慢半拍i 2021-02-03 17:30

I am new to nodejs. Can node resolve ~ (unix home directory) example ~foo, ~bar to /home/foo, /home/bar

> path.normalize(\'~mvaidya\') 
\'~mvaidya\'
> path.resolve(         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-03 17:48

    The reason this is not in Node is because ~ expansion is a bash (or shell) specific thing. It is unclear how to escape it properly. See this comment for details.

    There are various libraries offering this, most just a few lines of code...

    • https://npm.im/untildify ; doesn't do much more than os.homedir(), see index.js#L10

    • https://npm.im/expand-tilde ; basically uses os-homedir to achieve the same, see index.js#L12

    • https://npm.im/tilde-expansion ; this uses etc-passwd so doesn't seem very cross platform, see index.js#L21

    So you probably want to do this yourself.

提交回复
热议问题