6

I'm trying to check if a directory exists as part of a command-line app in node.js. However, fs doesn't seem to understand ~/. For example, the following returns false...

> fs.existsSync('~/Documents')
false

...but this returns true...

> fs.existsSync('/Users/gtmtg/Documents')
true

...even though they're both the same thing.

Why does this happen, and is there are workaround for this? Thanks in advance!

gtmtg
  • 3,010
  • 2
  • 22
  • 35
  • 3
    [It's a Bash feature called "tilde expansion". It's a function of the shell, not the OS.](http://stackoverflow.com/a/1660054/612202) – dan-lee Sep 16 '12 at 22:33

2 Answers2

9

That's because ~/ is supported by the command shell, not the file system APIs.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
0

As an alternative, the user's home path (~) is usually stored in the environment variable HOME. So you can try using something like this:

fs.existsSync(`${process.env.HOME}/Documents`);

Or, you can create a function to process the tilde character, like this:

function parseTildeHome(inputPath) {
  return inputPath.replace('~', process.env.HOME);
}

fs.existsSync(parseTildeHome('~/Documents'));
Tiago
  • 432
  • 4
  • 8