Expanding / Resolving ~ in node.js

node.jsPath

node.js Problem Overview


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('~mvaidya')
'/home/mvaidya/~mvaidya'
>

This response is wrong; I am hoping that ~mvaidya must resolve to /home/mvaidya

node.js Solutions


Solution 1 - node.js

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;
}

Solution 2 - node.js

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...

So you probably want to do this yourself.

Solution 3 - node.js

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.

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.

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

Solution 4 - node.js

An example:

const os = require("os");

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

Solution 5 - node.js

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

Solution 6 - node.js

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).

Solution 7 - node.js

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

I run on OSX, worked well.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionforvaidyaView Question on Stackoverflow
Solution 1 - node.jsPj DietzView Answer on Stackoverflow
Solution 2 - node.jswiresView Answer on Stackoverflow
Solution 3 - node.jsTony O'HaganView Answer on Stackoverflow
Solution 4 - node.jsBaiJiFeiLongView Answer on Stackoverflow
Solution 5 - node.jsMarcello de SalesView Answer on Stackoverflow
Solution 6 - node.jsJaredcheedaView Answer on Stackoverflow
Solution 7 - node.jsclayView Answer on Stackoverflow