Expanding / Resolving ~ in node.js

前端 未结 7 1720
慢半拍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 18:13

    This is a combination of some of the previous answers with a little more safety added in.

    /**
     * Resolves paths that start with a tilde to the user's home directory.
     *
     * @param  {string} filePath '~/GitHub/Repo/file.png'
     * @return {string}          '/home/bob/GitHub/Repo/file.png'
     */
    function resolveTilde (filePath) {
      const os = require('os');
      if (!filePath || typeof(filePath) !== 'string') {
        return '';
      }
    
      // '~/folder/path' or '~' not '~alias/folder/path'
      if (filePath.startsWith('~/') || filePath === '~') {
        return filePath.replace('~', os.homedir());
      }
    
      return filePath;
    }
    
    • Uses more modern os.homedir() instead of process.env.HOME.
    • Uses a simple helper function that can be called from anywhere.
    • Has basic type checking. You may want to default to returning os.homedir() if a non-string is passed in instead of returning empty string.
    • Verifies that path starts with ~/ or is just ~, to not replace other aliases like ~stuff/.
    • Uses a simple "replace first instance" approach, instead of less intuitive .slice(1).
    0 讨论(0)
提交回复
热议问题