Expanding / Resolving ~ in node.js

前端 未结 7 1718
慢半拍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.

    0 讨论(0)
  • 2021-02-03 18:00

    An example:

    const os = require("os");

    "~/Dropbox/sample/music".replace("~", os.homedir)

    0 讨论(0)
  • 2021-02-03 18:01

    I just needed it today and the only less-evasive command was the one from the os.

    $ node
    > os.homedir()
    '/Users/mdesales'
    

    I'm not sure if your syntax is correct since ~ is already a result for the home dir of the current user

    0 讨论(0)
  • 2021-02-03 18:02

    As QZ Support noted, you can use process.env.HOME on OSX/Linux. Here's a simple function with no dependencies.

    const path = require('path');
    function resolveHome(filepath) {
        if (filepath[0] === '~') {
            return path.join(process.env.HOME, filepath.slice(1));
        }
        return filepath;
    }
    
    0 讨论(0)
  • 2021-02-03 18:03

    Today I used https://github.com/sindresorhus/untildify

    I run on OSX, worked well.

    0 讨论(0)
  • 2021-02-03 18:07

    This NodeJS library supports this feature via an async callback. It uses the etc-passswd lib to perform the expansion so is probably not portable to Windows or other non Unix/Linux platforms.

    • https://www.npmjs.org/package/tilde-expansion
    • https://github.com/bahamas10/node-tilde-expansion

    If you only want to expand the home page for the current user then this lighter weight API may be all you need. It's also synchronous so simpler to use and works on most platforms.

    • https://www.npmjs.org/package/expand-home-dir

    Examples:

     expandHomeDir = require('expand-home-dir')
    
     expandHomeDir('~')
     // => /Users/azer
    
     expandHomeDir('~/foo/bar/qux.corge')
     // => /Users/azer/foo/bar/qux.corge
    

    Another related lib is home-dir that returns a user's home directory on any platform:

    https://www.npmjs.org/package/home-dir
    
    0 讨论(0)
提交回复
热议问题