parsePath.js
1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"use strict";
var isString = require("is-string");
function parsePath(pathString)
{
var filename,lastSlash;
var output = { dir:[], filename:null, leadingSlash:false };
// Length check is a speed optimization
if (isString(pathString)===true && pathString.length>0)
{
lastSlash = pathString.lastIndexOf("/");
if (lastSlash > -1)
{
// If slash is not last char
if (++lastSlash < pathString.length)
{
filename = pathString.substr(lastSlash);
// "/dir/to/filename.html", "/filename.html"
// "dir/to/filename.html", "filename.html"
if (filename!=="." && filename!=="..")
{
output.filename = filename;
pathString = pathString.substr(0, lastSlash);
}
// "/dir/to/..", "/dir/to/.", "/..", "/."
// "dir/to/..", "dir/to/.", "..", "."
else
{
pathString += "/";
}
}
output.dir = splitDirs(pathString);
}
// "..?var", "..#anchor", "..", "."
else if (pathString==="." || pathString==="..")
{
pathString += "/";
output.dir = splitDirs(pathString);
}
// "filename.html", "..filename.html", ".filename.html"
else
{
output.filename = pathString;
}
// For relative URLs -- clarifies if dir-relative or root-dir-relative
output.leadingSlash = (pathString[0] === "/");
}
return output;
}
/*
Splits a dir string into a dir Array and cleans up common issues.
*/
function splitDirs(dirString)
{
var dirs,i,len;
var output = [];
// Speed optimization
if (dirString !== "/")
{
dirs = dirString.split("/");
len = dirs.length;
for (i=0; i<len; i++)
{
// Cleanup -- splitting "/dir/" becomes ["","dir",""]
if (dirs[i] !== "")
{
output.push( dirs[i] );
}
}
}
return output;
}
module.exports = parsePath;