Question

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 ?

Was it helpful?

Solution

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)) {
    //...
}

OTHER TIPS

You could use

path.resolve(yourPath)===yourPath

If your path isn't normalized, use

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

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+'$'), '' );

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.

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) === '/';
};
    isRelative(url){
        return (/^(\.){1,2}(\/){1,2}$/.test(url.slice(0,3)) ||
        /(\/){1,2}(\.){1,2}(\/){1,2}/.test(url)); 
    }

This makes it easy to check whether a path is relative despite of absence of node path module API.

(/^(\.|~){1,2}(\/){1,2}$/.test(url.slice(0,3))

this part checks if the path string starts with the "./" or "../" or "~/". If it does, Boolean true is returned. Otherwise the next test is executed.

/(\/){1,2}(\.){1,2}(\/){1,2}/.test(url)

This just checks if the path string has either "/./" or "/../". and returns true on any and false on neither.

If any of the two tests is true then the path string is relative.

For windows.

    isRelative(url){
        return (/^(\.){1,2}(\\){1,2}$/.test(url.slice(0,3)) ||
        /(\\){1,2}(\.){1,2}(\\){1,2}/.test(url)); 
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top