gtmtg
gtmtg

Reputation: 3030

fs in Node.js Doesn't Understand ~/

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!

Upvotes: 6

Views: 1406

Answers (2)

Tiago
Tiago

Reputation: 442

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'));

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 312095

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

Upvotes: 9

Related Questions