-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
206 lines (156 loc) · 4.49 KB
/
index.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
var EE = require('events').EventEmitter
var parse = require('url').parse
var http = require('http')
var path = require('path')
var fs = require('fs')
var fileExists = require('utils-fs-exists')
var htmlls = require('html-ls')
var filed = require('filed')
var xtend = require('xtend')
var replace = require('stream-replace')
var defaults = require('./lib/config')
var RESPONSE_HEADERS = {'content-type': 'text/html;charset=utf-8'}
module.exports = createGlance
function Glance(options) {
EE.call(this)
options = xtend(defaults, options || {})
this.port = options.port
this.hideindex = options.hideindex
this.indices = options.indices
this.dir = path.resolve(options.dir)
this.nodot = options.nodot
return this
}
Glance.prototype = Object.create(EE.prototype)
Glance.prototype.start = function Glance$start() {
var self = this
self.server = http.createServer(function (req, res) {
self.serveRequest(req, res)
})
self.server.listen(self.port, emitStarted)
self.server.addListener('connection', function (con) {
con.setTimeout(500)
})
self.on('error', showError)
function emitStarted() {
self.emit('started', self.server)
}
}
Glance.prototype.stop = function Glance$stop() {
if (this.server) {
this.server.close()
}
}
Glance.prototype.serveRequest = function Glance$serveRequest(req, res) {
var request = {}
var self = this
request.fullPath = path.join(
self.dir,
decodeURIComponent(parse(req.url).pathname)
)
request.ip = req.socket.remoteAddress
request.method = req.method.toLowerCase()
request.response = res
// prevent traversing directories that are parents of the root
if (path.relative(self.dir, request.fullPath).startsWith('..')) {
return self.emit('error', 403, request, res)
}
if (request.method !== 'get') {
return self.emit('error', 405, request, res)
}
if (
self.nodot &&
request.fullPath.split(path.sep).some(function (dir) {
return dir.startsWith('.')
})
) {
return self.emit('error', 404, request, res)
}
fs.stat(request.fullPath, statFile)
function statFile(err, stat) {
if (err) {
return self.emit('error', 404, request, res)
}
if (!stat.isDirectory()) {
self.emit('read', request)
return filed(request.fullPath).pipe(res)
}
if (self.hideindex) {
return self.emit('error', 403, request, res)
}
if (!self.indices || !self.indices.length) {
return listFiles()
}
var indices = self.indices.slice()
findIndex(indices.shift())
function findIndex(indexTest) {
fileExists(path.join(request.fullPath, indexTest), check)
function check(hasIndex) {
if (hasIndex) {
req.url = req.url + '/' + indexTest
return self.serveRequest(req, res)
}
if (!indices.length) {
return listFiles()
}
findIndex(indices.shift())
}
}
function listFiles() {
var listPath = request.fullPath.replace(/\/$/, '')
res.writeHead(200, RESPONSE_HEADERS)
var listingHtml = '<h3>Directory Listing</h3>'
var listing = htmlls(listPath, {
hideDot: self.nodot,
transformHref: function (str) {
return encodeURI(str)
},
transformLinkText: function (str) {
return str.replace(/\</g, '<').replace(/\>/g, '>')
},
})
listing.on('data', function (buf) {
listingHtml += buf.toString()
})
listing.on('end', function () {
renderPage('Directory Listing', listingHtml, res)
})
return self.emit('read', request)
}
}
}
function showError(errorCode, req, res) {
res.writeHead(errorCode, RESPONSE_HEADERS)
var errorHtml = ''
var errorPage = fs.createReadStream(
path.join(__dirname, 'errors', errorCode + '.html')
)
errorPage.on('data', function (buf) {
errorHtml += buf.toString()
})
errorPage.on('end', function () {
var title = errorTitle(errorCode)
renderPage(title, errorHtml, res)
})
}
function renderPage(title, body, res) {
var layout = fs.createReadStream(
path.join(__dirname, 'errors/shared/layout.html')
)
layout
.pipe(replace(/{{\s*title\s*}}/g, title))
.pipe(replace(/{{\s*body\s*}}/g, body))
.pipe(res)
}
function errorTitle(errorCode) {
var mappings = {
404: 'File Not Found',
403: 'Forbidden',
405: 'Method Not Allowed',
500: 'Internal Server Error',
}
return mappings[errorCode.toString()]
}
function createGlance(options) {
return new Glance(options)
}