jeffheifetz
jeffheifetz

Reputation: 423

node.js fs.existsSync returns incorrect value for paths containing environment variables

I am trying to use fs.existsSync to check whether a file exists. When the full filesystem path is entered, it returns successfully. When the path contains an environment variable like ~/foo.bar or $HOME/foo.bar, it fails to find the file.

I have tried all of the methods from the path module to massage the path first, but nothing seems to work. I should note that the filepath is entered by the user either via command line or a JSON file.

I am aware that the environment variables live in process.env, but I was wondering if there is some way to handle this aside from a find/replace for every possible variable.

Upvotes: 2

Views: 4059

Answers (2)

josh3736
josh3736

Reputation: 145002

Environment variables are expanded by the shell. Node's fs methods make filesystem calls directly.

Read the variable you need out of process.env and use path.join to concatenate.

path.join(process.env.HOME, 'foo.bar');

(Keep in mind there is no HOME variable on Windows if you need to be cross-platform; I believe it's USERPROFILE.)


Since you're dealing with user input, you're going to have to parse the path components yourself.

First, normalize the input string and split it into an array.

var p = path.normalize(inputStr).split(path.sep);

If the first element is ~, replace it with the home directory.

if (p[0] == '~') p[0] = process.env.HOME || process.env.USERPROFILE; // Windows

Then loop over each element, and if it starts with $, replace it.

for (var i = 0; i < p.length; i++) {
    if (p[i][0] == '$') {
        var evar = p[i].substr(1);
        if (process.env[evar]) p[i] = process.env[evar];
    }
}

And finally, join the path array back together, re-normalizing:

path.join.apply(path, p);

Upvotes: 5

Zeke Nierenberg
Zeke Nierenberg

Reputation: 2206

Use process.env.HOME instead? Then use path.join to get the correct path.

fs.existsSync(path.join(process.env.HOME,"foo.bar"));

Upvotes: 2

Related Questions