Created
January 5, 2010 19:48
-
-
Save isaacs/269645 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var url = require("url"), | |
path = require("path"); | |
exports.parse = function (str) { | |
var parsed = url.parse(str); | |
return { | |
get scheme : function () { return parsed.protocol ? parsed.protocol.substr(-1) : undefined }, | |
get authorityRoot : function () { return parsed.slashes ? "//" : undefined }, | |
get authority : function () { return parsed.host }, | |
get userInfo : function () { return parsed.auth }, | |
get user : function () { return parsed.auth ? parsed.auth.split(":").shift() : undefined }, | |
get password : function () { return parsed.auth ? parsed.auth.split(":").slice(1).join(":") : undefined }, | |
get domain : function () { return parsed.hostname }, | |
get port : function () { return parsed.port }, | |
get path : function () { return parsed.pathname }, | |
get root : function () { return parsed.pathname && parsed.pathname.charAt(0) === "/" ? "/" : undefined }, | |
get directory : function () { return parsed.pathname ? | |
this.root ? path.dirname(parsed.pathname.substr(1)) : path.dirname(parsed.pathname) | |
: undefined }, | |
get file : function () { return parsed.pathname ? path.filename(parsed.pathname) : undefined }, | |
get query : function () { return parsed.query }, | |
get fragment : function () { return parsed.hash ? parsed.hash.substr(1) : undefined } | |
// setters left as an exercise for the reader. | |
}; | |
}; | |
exports.resolveObject = function (source, dest) { | |
return exports.parse(exports.resolve(source, dest)); | |
}; | |
exports.resolve = function (source, dest) { | |
return url.resolve(source, dest); | |
}; | |
exports.format = function (obj) { | |
if (obj.href) obj = exports.parse(obj.href); | |
return ( | |
obj.scheme ? obj.scheme + ":" : "" | |
) + ( | |
obj.authorityRoot || "" | |
) + ( | |
obj.authority || "" | |
) + ( | |
obj.path || "" | |
) + ( | |
obj.query ? "?" + obj.query : "" | |
) + ( | |
obj.fragement ? "#" + obj.fragment : "" | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment