forked from mjackson/strata
/
static.js
107 lines (91 loc) · 3.9 KB
/
static.js
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
101
102
103
104
105
106
107
var path = require("path"),
fs = require("fs"),
mime = require("mime"),
strata = require("./index");
/**
* A middleware for serving files efficiently from the given +root+ directory
* according to path contained in the pathInfo environment variable. The +index+
* argument specifies what file will be served if the request targets a
* directory. It may be a single filename (e.g. "index.html") or an array of
* names to be tried in order (e.g. ["index.html", "index.htm"]).
*
* If a matching file cannot be found, the request is forwarded to the
* downstream app. Otherwise, the file is streamed through to the callback.
*/
module.exports = function (app, root, index) {
if (typeof root != "string") {
throw new strata.Error("Invalid root directory");
}
if (path.existsSync(root)) {
var stats = fs.statSync(root);
if (!stats.isDirectory()) {
throw new strata.Error('"' + root + '" is not a directory')
}
} else {
throw new strata.Error('Directory "' + root + '" does not exist');
}
if (index && typeof index == "string") {
index = [index];
}
return function stat(env, callback) {
var fullPath = path.join(root, env.pathInfo);
path.exists(fullPath, function (exists) {
if (exists) {
fs.stat(fullPath, function (err, stats) {
if (err && strata.handleError(err, env, callback)) {
return;
}
if (stats.isFile()) {
sendFile(callback, fullPath, stats);
} else if (stats.isDirectory() && index) {
// If the request targets a directory check all index
// files to see if we can serve any of them.
var indexExists = {};
function sendFirstExisting() {
var found = false,
indexPath;
for (var i = 0, len = index.length; !found && i < len; ++i) {
indexPath = path.join(fullPath, index[i]);
if (indexExists[indexPath]) {
fs.stat(indexPath, function (err, stats) {
if (err && strata.handleError(err, env, callback)) {
return;
}
sendFile(callback, indexPath, stats);
});
found = true;
}
}
if (!found) {
app(env, callback);
}
}
var checked = 0;
for (var i = 0, len = index.length; i < len; ++i) {
(function (indexPath) {
path.exists(indexPath, function (exists) {
indexExists[indexPath] = exists;
checked += 1;
if (checked == len) {
sendFirstExisting();
}
});
})(path.join(fullPath, index[i]));
}
} else {
app(env, callback);
}
});
} else {
app(env, callback);
}
});
}
}
function sendFile(callback, path, stats) {
callback(200, {
"Content-Type": mime.lookup(path),
"Content-Length": stats.size.toString(),
"Last-Modified": stats.mtime.toUTCString()
}, fs.createReadStream(path));
}