How to check if a path is absolute or relative

20,323

Solution 1

Since node version 0.12.0 you can use the path.isAbsolute(path) function from the path module.

i.e:

var path = require('path');
if(path.isAbsolute(myPath)) {
    //...
}

Solution 2

You could use

path.resolve(yourPath)===yourPath

If your path isn't normalized, use

path.resolve( yourPath ) == path.normalize( yourPath )

Solution 3

As commented to dystroy's answer, the proposed solutions don't work if an absolute path is not already normalized (for example the path: ///a//..//b//./).

A correct solution is:

path.resolve(yourPath) === path.normalize(yourPath)

As Marc Diethelm suggests in the comments, this has still some issues, since path.resolve removes trailing slashes while path.normalize doesn't.

I'm not sure how these function exactly behave (as you can read in the comments), anyway the following snippet seem to work fine at least in Linux environments:

path.resolve(yourPath) === path.normalize(yourPath).replace( RegExp(path.sep+'$'), '' );

Solution 4

This is a little convoluted, but the most robust way I've found using just the (pre node 0.12.0) path module

function isAbsolute(p) {
    return path.normalize(p + '/') === path.normalize(path.resolve(p) + '/');
}

It should be noted that path.isAbsolute exists from node 0.12.0 onwards.

Solution 5

I have no idea about node.js, but you can see the source of path.js in github: https://github.com/joyent/node/blob/master/lib/path.js

You can see:

// windows version
exports.isAbsolute = function(path) {
    var result = splitDeviceRe.exec(path),
    device = result[1] || '',
    isUnc = device && device.charAt(1) !== ':';
    // UNC paths are always absolute
    return !!result[2] || isUnc;
};

And:

// posix version
exports.isAbsolute = function(path) {
    return path.charAt(0) === '/';
};
Share:
20,323
Manuel Di Iorio
Author by

Manuel Di Iorio

Updated on July 09, 2022

Comments

  • Manuel Di Iorio
    Manuel Di Iorio almost 2 years

    UNIX absolute path starts with '/', whereas Windows starts with alphabet 'C:' or '\'. Does node.js has a standard multiplatform function to check if a path is absolute or relative ?

  • Denys Séguret
    Denys Séguret about 10 years
    There's also a isAbsolute function in the source even if I don't find it in docs and it doesn't seem to be available : github.com/joyent/node/blob/master/lib/path.js#L206
  • Manuel Di Iorio
    Manuel Di Iorio about 10 years
    Yep, I don't know why there isn't in the doc but for now I think that I will use your response, for security.
  • Denys Séguret
    Denys Séguret about 10 years
    The function is in fact in unstable (0.11) but not in the last stable.
  • peoro
    peoro almost 10 years
    This doesn't work if yourPath isn't already normalized (eg: it doesn't work with ///a//..//b//. The corrent solution is: path.resolve( yourPath ) == path.normalize( yourPath )
  • Marc Diethelm
    Marc Diethelm over 9 years
    However since normalize preserves trailing slashes your solution needs to be enhanced. path.resolve(_yourPath) === path.normalize(_yourPath).replace(/[\/|\\]$/, ''), will work reliably.
  • peoro
    peoro over 9 years
    @MarcDiethelm: you're very right, I never noticed. I'll try to fix the answer taking into account your suggestion! Anyway your solution still doesn't work perfectly, for example it fails with '/\\'. Is there any specific reason to remove trailing backslashes? Is it to support windows paths or what else?
  • Marc Diethelm
    Marc Diethelm over 9 years
    exactly checking for a trailing backslash is need on Windows. re: it fails with '/\\'. I don't understand, can you elobarate? Is that supposed to be a path you test for?!
  • peoro
    peoro over 9 years
    @MarcDiethelm: yes, exactly. I'm running Node on a Linux machine. If I pass to your function the '/\\' string, path.resolve('/\\') returns '/\\', while path.normalize('/\\').replace(/[\/|\\]$/, '') returns '/'. The line I added to this response seems to work fine for me on Linux, but might be other issues (maybe on Windows?)
  • Marc Diethelm
    Marc Diethelm over 9 years
    The path '/\\' seems like a real edge case for me. Maybe try unescaping first? I'm not a fan of invoking the RegExp constructor with all its overhead here. path.sep looks nice at first. But basically we just want to remove ANY (Windows or else) trailing slashes before comparing. Here's my amended version that works for a root '/' path too: path.resolve(yourPath) === path.normalize(yourPath).replace(/(.+)([\/|\\])$/, '$1').
  • krex
    krex over 9 years
    This answer is a bit ambiguous. What does this check prove?
  • vulcan raven
    vulcan raven over 9 years
    This does not work with node v0.10.35 on Windows. If you have an absolute path without drive letter, this will fail because path.normalize() does not prepend drive letter.
  • TomDotTom
    TomDotTom almost 9 years
    I believe the following is more robust: function isAbsolute(p) { return path.normalize(p + '/') === path.normalize(path.resolve(p) + '/'); }
  • Alexander Mills
    Alexander Mills about 8 years
    note that isAbsolute seems to return true for any path that starts with /, whether on Windows or Mac (not sure about *nix)
  • Abhishek Pandey
    Abhishek Pandey over 7 years
    Please Explain what you did.
  • Kawd
    Kawd almost 6 years
    As Alexander Mills pointed out, this answer is wrong. If your relative path starts with a / (as all relative paths usually do) then this method will return true, which is wrong. I don't know why it was selected as the correct answer, this is dangerous and makes SO unreliable.
  • Chris Arnesen
    Chris Arnesen over 5 years
    @SproutCoder This answer is correct. Maybe you're thinking of relative paths in the sense of http URLs? The Node.js utility path.isAbsolute is meant to be used for filesystem paths where an "absolute path" by definition starts with a slash. See linfo.org/path.html, for example.
  • ErikE
    ErikE about 5 years
    How can you define paths starting with ~ as relative? They may be relative, but not to the current directory. It seems like there are really three states and isAbsolute is a bad function because it misleads. Paths starting with ~ are stable and don't change depending on the current directory; in this sense they are absolute...
  • ErikE
    ErikE about 5 years
    Be aware that isAbsolute, when handed paths beginning with ~ on unix or unix-like systems, will return false. While those paths are indeed relative to the current user's user directory, they are not relative to the current directory, so changing directories doesn't affect what they resolve to. In this sense, those paths are absolute, which could be surprising to some people.