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 ?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- Keeping track of variable instances
This is a little convoluted, but the most robust way I've found using just the (pre node 0.12.0) path module
It should be noted that path.isAbsolute exists from node 0.12.0 onwards.
This makes it easy to check whether a path is relative despite of absence of node path module API.
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.
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.
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:
And:
You could use
If your path isn't normalized, use
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:
As Marc Diethelm suggests in the comments, this has still some issues, since
path.resolve
removes trailing slashes whilepath.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:
Since node version 0.12.0 you can use the
path.isAbsolute(path)
function from the path module.i.e: