Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Licensed as MIT
- /** Filter and normalize (partly relative) path. The resulting path does not contain multiple slashes and will always be absolute (starting with a slash). Intermediate ../ are expanded (resolved). If a path specifies more ../ than possible an exception is thrown.
- * @param {String} path... one path or multiple path fragments (as multipe arguments)
- * @return {String} normalized and filtered, absolute path with no trailing slash
- */
- function normalizePath(str){
- var path = "", i;
- if (arguments.length > 1) {
- for (i = 0; i < arguments.length; i++) {
- path += "/" + arguments[i];
- }
- return normalizePath(path);
- }
- path = "/" + str;
- path = path.replace(/\/+$/g, "");
- path = path.replace(/\/+/g, "/");
- while (path.indexOf("..") > -1 && path.indexOf("/..") != 0) {
- path = path.replace(/[^\.\/]+\/\.\.\//g, "");
- }
- if (path.indexOf("/..") === 0) {
- throw new Error("Malformed path '"+ str +"' (does not resolve to absolute path: '"+ path +"')");
- }
- path = path.replace(/\.\//g, "");
- return path;
- }
Add Comment
Please, Sign In to add comment