path.js
1.6 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
92
93
94
95
96
97
98
99
100
"use strict";
function isDirectoryIndex(resource, options)
{
var verdict = false;
options.directoryIndexes.every( function(index)
{
if (index === resource)
{
verdict = true;
return false;
}
return true;
});
return verdict;
}
function parsePath(urlObj, options)
{
var path = urlObj.path.absolute.string;
if (path)
{
var lastSlash = path.lastIndexOf("/");
if (lastSlash > -1)
{
if (++lastSlash < path.length)
{
var resource = path.substr(lastSlash);
if (resource!=="." && resource!=="..")
{
urlObj.resource = resource;
path = path.substr(0, lastSlash);
}
else
{
path += "/";
}
}
urlObj.path.absolute.string = path;
urlObj.path.absolute.array = splitPath(path);
}
else if (path==="." || path==="..")
{
// "..?var", "..#anchor", etc ... not "..index.html"
path += "/";
urlObj.path.absolute.string = path;
urlObj.path.absolute.array = splitPath(path);
}
else
{
// Resource-only
urlObj.resource = path;
urlObj.path.absolute.string = null;
}
urlObj.extra.resourceIsIndex = isDirectoryIndex(urlObj.resource, options);
}
// Else: query/hash-only or empty
}
function splitPath(path)
{
// TWEAK :: condition only for speed optimization
if (path !== "/")
{
var cleaned = [];
path.split("/").forEach( function(dir)
{
// Cleanup -- splitting "/dir/" becomes ["","dir",""]
if (dir !== "")
{
cleaned.push(dir);
}
});
return cleaned;
}
else
{
// Faster to skip the above block and just create an array
return [];
}
}
module.exports = parsePath;