Created
January 5, 2010 19:32
-
-
Save isaacs/269633 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
// url-rfc module | |
// Just like node's url module, but using the same names used in various UR[LI] RFCs | |
var url = require("url"), | |
path = require("path"); | |
exports.parse = function (str) { | |
var parsed = url.parse(str); | |
var out = {}; | |
if (parsed.protocol) out.scheme = parsed.protocol.substr(-1); | |
if (parsed.slashes) out.authorityRoot = "//"; | |
if (parsed.host) { | |
out.authority = parsed.host; | |
if (parsed.auth) { | |
out.userInfo = parsed.auth; | |
var split = parsed.auth.split(":"); | |
out.user = split.shift() | |
out.password = split.join(":"); | |
} | |
if (parsed.hostname) out.domain = parsed.hostname; | |
if (parsed.port) out.port = parsed.port; | |
} | |
if (parsed.pathname) { | |
out.path = parsed.pathname; | |
if (parsed.pathname.charAt(0) === "/") { | |
out.root = "/"; | |
} | |
out.directory = path.dirname(out.root ? parsed.pathname.substr(1) : parsed.pathname); | |
out.file = path.filename(parsed.pathname); | |
} | |
if (parsed.query) out.query = parsed.query; | |
if (parsed.hash) out.fragment = parsed.hash.substr(1); | |
return out; | |
}; | |
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