How to check if a path is absolute or relative How to check if a path is absolute or relative node.js node.js

How to check if a path is absolute or relative


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


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