expediate 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.gitignore ADDED
@@ -0,0 +1,14 @@
1
+ # Git ignore
2
+ # ------------------------
3
+ *
4
+ !*/
5
+ # ------------------------
6
+
7
+ node_modules/
8
+ !*.js
9
+ !*.html
10
+ !package.json
11
+ !.git*
12
+ !.npm*
13
+ !dist/**/*
14
+
package/.npmignore ADDED
@@ -0,0 +1,14 @@
1
+ # Npm ignore
2
+ # ------------------------
3
+ *
4
+ !*/
5
+ # ------------------------
6
+
7
+ node_modules/
8
+ !*.js
9
+ !*.html
10
+ !package.json
11
+ !.git*
12
+ !.npm*
13
+ !dist/**/*
14
+
package/README.md ADDED
@@ -0,0 +1,83 @@
1
+ # Expediate
2
+
3
+ This small library serve as a router facility for a web server.
4
+ For compatibility reason it keep the exact same interface as express.js,
5
+ however it doesn't intent to provide all the features.
6
+
7
+ [![NPM Version][npm-image]][npm-url]
8
+ [![NPM Downloads][downloads-image]][downloads-url]
9
+ [![Linux Build][travis-image]][travis-url]
10
+ [![Windows Build][appveyor-image]][appveyor-url]
11
+ [![Test Coverage][coveralls-image]][coveralls-url]
12
+
13
+ ```js
14
+ const expediate = require('expediate')
15
+ const app = expediate()
16
+
17
+ app.get('/', function (req, res) {
18
+ res.send('Hello World')
19
+ })
20
+
21
+ app.listen(3000)
22
+ ```
23
+
24
+ The main reason for this package is that expressjs grow to become extra
25
+ complicated with tons of dependencies. Expediate aims to keep thing simple
26
+ while retaining the most widely used features.
27
+
28
+ ## Installation
29
+
30
+ This is a [Node.js](https://nodejs.org/en/) module available through the
31
+ [npm registry](https://www.npmjs.com/).
32
+
33
+ Before installing, [download and install Node.js](https://nodejs.org/en/download/).
34
+
35
+ If this is a brand new project, make sure to create a `package.json` first with
36
+ the [`npm init` command](https://docs.npmjs.com/creating-a-package-json-file).
37
+
38
+ Installation is done using the
39
+ [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
40
+
41
+ ```bash
42
+ $ npm install expediate
43
+ ```
44
+
45
+ ## Usage
46
+
47
+
48
+ ### Middleware
49
+
50
+ json => Parse Json body
51
+ static => Serve static files
52
+ urlencdeded => Parse url encoded
53
+
54
+ ```js
55
+ var apiApp = expediate()
56
+ apiApp.use('/myEndpoint', ...)
57
+
58
+ var app = expediate();
59
+ var app.use('/api', apiApp);
60
+
61
+ app.listen(80)
62
+ app.listen(443, { key: 'xx', cert: 'xx' })
63
+ apiApp.listen(8900) // Only api
64
+ ```
65
+
66
+
67
+
68
+ ## License
69
+
70
+ [MIT](LICENSE)
71
+
72
+
73
+ [npm-image]: https://img.shields.io/npm/v/expediate.svg
74
+ [npm-url]: https://npmjs.org/package/expediate
75
+ [downloads-image]: https://img.shields.io/npm/dm/expediate.svg
76
+ [downloads-url]: https://npmcharts.com/compare/expediate?minimal=true
77
+ [travis-image]: https://img.shields.io/travis/axfab/expediate/master.svg?label=linux
78
+ [travis-url]: https://travis-ci.org/axfab/expediate
79
+ [appveyor-image]: https://img.shields.io/appveyor/ci/axfab/expediate/master.svg?label=windows
80
+ [appveyor-url]: https://ci.appveyor.com/project/axfab/expediate
81
+ [coveralls-image]: https://img.shields.io/coveralls/axfab/expediate/master.svg
82
+ [coveralls-url]: https://coveralls.io/r/axfab/expediate?branch=master
83
+
package/index.js ADDED
@@ -0,0 +1,266 @@
1
+ /* Copyright 2021 Fabien Bavent
2
+ *
3
+ * Permission is hereby granted, free of charge, to any person obtaining a
4
+ * copy of this software and associated documentation files (the "Software"),
5
+ * to deal in the Software without restriction, including without limitation
6
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
7
+ * and/or sell copies of the Software, and to permit persons to whom the
8
+ * Software is furnished to do so, subject to the following conditions:
9
+ *
10
+ * The above copyright notice and this permission notice shall be included
11
+ * in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19
+ * DEALINGS IN THE SOFTWARE.
20
+ */
21
+ 'use strict';
22
+
23
+ const http = require('http'),
24
+ https = require('https'),
25
+ serveStatic = require('./static.js');
26
+
27
+ /**
28
+ * Prepare an layer object to define a new route
29
+ *
30
+ * @param {String} method
31
+ * @param {String} [path]
32
+ * @param {Listener} listener
33
+ * @return {Layer}
34
+ */
35
+ function buildRouteLayer(method, path, listener) {
36
+ if (method)
37
+ method = method.toUpperCase();
38
+ if (typeof path === 'function') {
39
+ listener = path;
40
+ path = '/';
41
+ }
42
+ let parts = path.split('/').filter(x => x.length > 0);
43
+ return { method, path, parts, listener };
44
+ };
45
+
46
+ /**
47
+ * Check if a request match the current route(layer)
48
+ *
49
+ * In case the request match the route, we update the request
50
+ * path field and the queries.route map depending on route parameters
51
+ *
52
+ * @param {Layer} layer
53
+ * @param {http.ClientRequest} req
54
+ * @param {String[]} parts
55
+ * @return {Bool}
56
+ */
57
+ function matchRouteLayer(layer, req, parts) {
58
+ if (layer.method && layer.method != req.method)
59
+ return false;
60
+ let params = {}
61
+ for (let i = 0; ; ++i) {
62
+ if (layer.parts.length <= i) {
63
+ req.path = '/' + parts.slice(i).join('/');
64
+ req.queries.route = params;
65
+ return true;
66
+ } else if (parts.length <= i)
67
+ return false;
68
+ else if (layer.parts[i][0] == ':')
69
+ params[layer.parts[i].substring(1)] = parts[i];
70
+ else if (layer.parts[i] != parts[i])
71
+ return false;
72
+ }
73
+ };
74
+
75
+ /**
76
+ * Extends the request and response object of a http request
77
+ * with parameters and helper.
78
+ *
79
+ * @param {http.ClientRequest} req
80
+ * @param {http.ServerResponse} res
81
+ */
82
+ function updateHttpObject(req, res) {
83
+ if (req.queries)
84
+ return
85
+ req.queries = {};
86
+
87
+ let qry = new URL(`http://${req.headers.host}${req.url}`)
88
+ req.originalUrl = req.url;
89
+ req.path = qry.pathname
90
+
91
+ // Parse URL-encoded data
92
+ let params = {};
93
+ for(var pair of qry.searchParams.entries())
94
+ params[pair[0]] = pair[1];
95
+ req.queries.url = params;
96
+
97
+ // Parse cookies
98
+ if (req.cookies == null) {
99
+ req.cookies = {};
100
+ var cookies = req.headers.cookie;
101
+ if (cookies) {
102
+ cookies = cookies.split(';')
103
+ .map(x => x.replace(/^\s+|\s+$/g, '').split('='));
104
+ for (var k in cookies) {
105
+ let key = cookies[k][0]
106
+ let val = cookies[k][1]
107
+ req.cookies[key] = val;
108
+ if (typeof val == 'string') {
109
+ // TODO s: Cookie is signed, j: Cookie is a JSON
110
+ }
111
+ }
112
+ }
113
+ }
114
+
115
+
116
+ res.setHeader('X-Powered-By', 'Expediate');
117
+
118
+ res.send = (data) => {
119
+ res.write(data);
120
+ res.end();
121
+ }
122
+
123
+ res.status = (code, headers) => {
124
+ if (headers)
125
+ for (var k in headers)
126
+ res.setHeader(k, headers[k])
127
+ res.writeHead(code)
128
+ return res;
129
+ };
130
+
131
+ res.redirect = (url) => {
132
+ let status = 302;
133
+ res.setHeader('location', url);
134
+ res.writeHead(status)
135
+ res.write(`Found. Redirecting to ${url}`);
136
+ res.end();
137
+ };
138
+
139
+ res.cookie = function (name, value, options) {
140
+ var opts = options || {};
141
+
142
+ if (opts.signed && !res.req.secret)
143
+ throw new Error('cookieParser("secret") required for signed cookies');
144
+
145
+ var val = typeof value === 'object'
146
+ ? 'j:' + JSON.stringify(value)
147
+ : String(value);
148
+
149
+ if (opts.signed)
150
+ val = 's:' + sign(val, res.req.secret);
151
+
152
+ let txt = `${name}=${String(val)}`
153
+
154
+ if ('maxAge' in opts) {
155
+ opts.expires = new Date(Date.now() + opts.maxAge);
156
+ opts.maxAge /= 1000;
157
+ }
158
+
159
+ if (opts.path == null)
160
+ opts.path = '/';
161
+ txt += `; Path=${opts.path}`
162
+
163
+ res.setHeader('Set-Cookie', txt);
164
+ return res;
165
+ };
166
+
167
+ };
168
+
169
+ // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
170
+
171
+ module.exports = Router;
172
+
173
+ /**
174
+ * This function create a new router function as a web listener.
175
+ */
176
+ function Router() {
177
+
178
+ const routes = [];
179
+
180
+ const listener = function(req, res, done) {
181
+ const method = req.method;
182
+ const url = req.url;
183
+ let idx = 0;
184
+ updateHttpObject(req, res);
185
+ const parts = req.path.split('/').filter(x => x.length > 0);
186
+
187
+ const next = () => {
188
+ while (idx < routes.length) {
189
+ let layer = routes[idx++];
190
+ if (matchRouteLayer(layer, req, parts))
191
+ return layer.listener(req, res, next);
192
+ }
193
+
194
+ if (done)
195
+ return done();
196
+ return res.status(404).end(`Cannot ${method} ${url}`);
197
+ }
198
+
199
+ try {
200
+ next();
201
+ } catch (e) {
202
+ console.warn(e)
203
+ res.status(500).end(`Error ${method} ${url}`)
204
+ }
205
+ };
206
+
207
+ listener.use = (p, l) => routes.push(buildRouteLayer(null, p, l));
208
+ listener.all = (p, l) => routes.push(buildRouteLayer(null, p, l));
209
+ listener.get = (p, l) => routes.push(buildRouteLayer('GET', p, l));
210
+ listener.put = (p, l) => routes.push(buildRouteLayer('PUT', p, l));
211
+ listener.post = (p, l) => routes.push(buildRouteLayer('POST', p, l));
212
+ listener.delete = (p, l) => routes.push(buildRouteLayer('DELETE', p, l));
213
+ listener.patch = (p, l) => routes.push(buildRouteLayer('PATCH', p, l));
214
+
215
+ listener.listen = (port, opts, cb) => {
216
+ if (typeof opts === 'function') {
217
+ cb = opts;
218
+ opts = null;
219
+ }
220
+ if (opts && opts.key && opts.cert)
221
+ https.createServer(opts, listener).listen(port, cb);
222
+ else
223
+ http.createServer(listener).listen(port, cb);
224
+ };
225
+
226
+ return listener;
227
+ };
228
+
229
+ // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
230
+
231
+ Router.logger = () => {
232
+ return (req, res, next) => {
233
+ const nclr = '\x1b[0m';
234
+ const colors = [
235
+ '\x1b[31m', '\x1b[33m', '\x1b[32m', '\x1b[33m', '\x1b[31m', '\x1b[91m'];
236
+ const rec = new Intl.DateTimeFormat('en-GB', {
237
+ month: 'short',
238
+ day:'2-digit',
239
+ hour:'2-digit',
240
+ minute:'2-digit'}).format();
241
+ const path = req.path;
242
+ req.received = new Date().getTime();
243
+ res.on('finish', ev => {
244
+ req.elapsed = new Date().getTime() - req.received;
245
+ const clr = colors[parseInt(res.statusCode / 100)];
246
+ const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
247
+ const user = req.session ? `${req.session.username}/${req.session.ssid}` : '-'
248
+ const status = `${clr}${res.statusCode}${nclr}`
249
+ const elp = `${req.elapsed} ms`
250
+ console.log(`${rec} ${status} ${req.method} ${path} ${ip} <${user}> ${elp}`);
251
+ })
252
+ next();
253
+ };
254
+ };
255
+
256
+ Router.static = serveStatic;
257
+
258
+ Router.session = (opts) => {
259
+ return (req, res, next) => {
260
+ let ssid = req.cookies.ssid;
261
+ req.session = opts.openSession(ssid);
262
+ if (ssid != req.session.ssid)
263
+ res.cookie('ssid', req.session.ssid);
264
+ next();
265
+ };
266
+ };
package/package.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "expediate",
3
+ "version": "0.0.2",
4
+ "description": "Fast and simple, minimalist web framework",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "author": "Fabien Bavent <fabien.bavet@gmail.com>",
10
+ "license": "MIT",
11
+ "dependencies": {
12
+ "mime": "^1.6.0"
13
+ }
14
+ }
package/sample.js ADDED
@@ -0,0 +1,9 @@
1
+
2
+ const expediate = require('./index.js')
3
+ app = expediate();
4
+
5
+
6
+ app.use('/', expediate.logger())
7
+ app.use('/', expediate.static('.'))
8
+ app.listen(80)
9
+
package/static.js ADDED
@@ -0,0 +1,388 @@
1
+ /* Copyright 2021 Fabien Bavent
2
+ *
3
+ * Permission is hereby granted, free of charge, to any person obtaining a
4
+ * copy of this software and associated documentation files (the "Software"),
5
+ * to deal in the Software without restriction, including without limitation
6
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
7
+ * and/or sell copies of the Software, and to permit persons to whom the
8
+ * Software is furnished to do so, subject to the following conditions:
9
+ *
10
+ * The above copyright notice and this permission notice shall be included
11
+ * in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19
+ * DEALINGS IN THE SOFTWARE.
20
+ */
21
+ 'use strict';
22
+
23
+ const fs = require('fs'),
24
+ path = require('path');
25
+ const mime = require('mime');
26
+
27
+ // Regular expression to match a path with a directory up component.
28
+ const UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/
29
+
30
+ const HTTP = {
31
+ NOT_MODIFIED: res => httpSend(res, 304),
32
+ FORBIDDEN: res => httpSend(res, 403, {
33
+ 'Content-Security-Policy': "default-src 'none'",
34
+ 'X-Content-Type-Options': 'nosniff'
35
+ }, 'Forbidden'),
36
+ NOT_FOUND: res => httpSend(res, 404, {
37
+ // 'Content-Type': 'text/html; charset=UTF-8',
38
+ 'Content-Security-Policy': "default-src 'none'",
39
+ 'X-Content-Type-Options': 'nosniff'
40
+ }, 'Not Found'),
41
+ NOT_ALLOWED: res => httpSend(res, 405, { 'Allow': 'GET, HEAD' }),
42
+ PRECONDITION_FAILS: res => httpSend(res, 412, {
43
+ 'Content-Security-Policy': "default-src 'none'",
44
+ 'X-Content-Type-Options': 'nosniff'
45
+ }, 'Precondition Failed'),
46
+ INTERNAL_ERROR: (res, err) => httpSend(res, 500, {
47
+ 'Content-Security-Policy': "default-src 'none'",
48
+ 'X-Content-Type-Options': 'nosniff'
49
+ }, `Internal error: ${err}`),
50
+ };
51
+
52
+ // Destroy a read stream properly
53
+ function destroyReadStream(stream) {
54
+ stream.destroy()
55
+ if (typeof stream.close === 'function') {
56
+ // node.js core bug work-around
57
+ stream.on('open', _ => {
58
+ if (typeof stream.fd === 'number')
59
+ stream.close()
60
+ })
61
+ }
62
+ }
63
+
64
+ function removeContentHeaders(res) {
65
+ var keys = Object.keys(res.getHeaders() || {});
66
+ for (let key of keys) {
67
+ if (key.substr(0, 8) === 'content-' && key != 'content-location')
68
+ res.removeHeader(key)
69
+ }
70
+ }
71
+
72
+ // Create a simple ETag based on file metadata
73
+ function createETag(stat) {
74
+ var mtime = stat.mtime.getTime().toString(16)
75
+ var size = stat.size.toString(16)
76
+ return 'W/"' + size + '-' + mtime + '"'
77
+ }
78
+
79
+ // Basic utility for default answers
80
+ function httpSend (res, code, headers, body) {
81
+ headers = headers || {}
82
+ body = body || ''
83
+ res.statusCode = code;
84
+ for (let k in headers)
85
+ res.setHeader(k.toString(), headers[k].toString())
86
+ res.setHeader('Content-Length', Buffer.byteLength(body))
87
+ if (body)
88
+ res.write(body);
89
+ res.end();
90
+ }
91
+
92
+ // Parse a HTTP token list.
93
+ function parseTokenList (str) {
94
+ var end = 0
95
+ var list = []
96
+ var start = 0
97
+
98
+ // gather tokens
99
+ for (var i = 0, len = str.length; i < len; i++) {
100
+ switch (str.charCodeAt(i)) {
101
+ case 0x20: /* */
102
+ if (start === end) {
103
+ start = end = i + 1
104
+ }
105
+ break
106
+ case 0x2c: /* , */
107
+ list.push(str.substring(start, end))
108
+ start = end = i + 1
109
+ break
110
+ default:
111
+ end = i + 1
112
+ break
113
+ }
114
+ }
115
+
116
+ // final token
117
+ list.push(str.substring(start, end))
118
+
119
+ return list
120
+ }
121
+
122
+ // Parse an HTTP Date into a number.
123
+ function parseHttpDate (date) {
124
+ var timestamp = date && Date.parse(date)
125
+
126
+ return typeof timestamp === 'number'
127
+ ? timestamp
128
+ : NaN
129
+ }
130
+
131
+ function hasCondition(req) {
132
+ return req['if-match'] ||
133
+ req['if-unmodified-since'] ||
134
+ req['if-none-match'] ||
135
+ req['if-modified-since']
136
+ }
137
+
138
+ function conditionMatch(req, res) {
139
+
140
+ // if-match
141
+ const match = req['if-match']
142
+ if (match) {
143
+ const etag = res['etag']
144
+ if (match === etag || match === '*')
145
+ return true;
146
+ for (let tag of parseTokenList(match))
147
+ if (match === tag || match === 'W/' + tag || 'W/' + match === tag)
148
+ return true;
149
+ }
150
+
151
+ // if-unmodified-since
152
+ const lastModified = parseHttpDate(res['last-modified'])
153
+ const unmodifiedSince = parseHttpDate(req['if-modified-since'])
154
+ if (!isNaN(unmodifiedSince) && !isNaN(lastModified))
155
+ return lastModified <= unmodifiedSince
156
+
157
+
158
+ return false
159
+ }
160
+
161
+ // Check freshness of the response using request and response headers.
162
+ function isCacheFresh (req, res) {
163
+ const CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/
164
+ // fields
165
+ var modifiedSince = req['if-modified-since']
166
+ var noneMatch = req['if-none-match']
167
+
168
+ // unconditional request
169
+ if (!modifiedSince && !noneMatch) {
170
+ return false
171
+ }
172
+
173
+ // Always return stale when Cache-Control: no-cache
174
+ // to support end-to-end reload requests
175
+ // https://tools.ietf.org/html/rfc2616#section-14.9.4
176
+ var cacheControl = req['cache-control']
177
+ if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) {
178
+ return false
179
+ }
180
+
181
+ // if-none-match
182
+ if (noneMatch && noneMatch !== '*') {
183
+ var etag = res['etag']
184
+
185
+ if (!etag) {
186
+ return false
187
+ }
188
+
189
+ var etagStale = true
190
+ var matches = parseTokenList(noneMatch)
191
+ for (var i = 0; i < matches.length; i++) {
192
+ var match = matches[i]
193
+ if (match === etag || match === 'W/' + etag || 'W/' + match === etag) {
194
+ etagStale = false
195
+ break
196
+ }
197
+ }
198
+
199
+ if (etagStale) {
200
+ return false
201
+ }
202
+ }
203
+
204
+ // if-modified-since
205
+ if (modifiedSince) {
206
+ var lastModified = res['last-modified']
207
+ var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince))
208
+
209
+ if (modifiedStale) {
210
+ return false
211
+ }
212
+ }
213
+
214
+ return true
215
+ }
216
+
217
+ function sendFile(req, res, pathname, stat, opts) {
218
+ const len = stat.size
219
+ const etag = createETag(stat)
220
+
221
+ if (opts.setHeaders)
222
+ opts.setHeaders(res);
223
+
224
+ // set cache-control
225
+ if (!res.getHeader('Cache-Control') && opts.maxage) {
226
+ var cacheControl = 'public, max-age=' + Math.floor(opts.maxage / 1000)
227
+ if (opts.immutable === true)
228
+ cacheControl += ', immutable'
229
+ res.setHeader('Cache-Control', cacheControl)
230
+ }
231
+
232
+ if (!res.getHeader('Last-Modified') && opts.lastModified !== false)
233
+ res.setHeader('Last-Modified', stat.mtime.toUTCString())
234
+
235
+ if (!res.getHeader('ETag') && opts.etag !== false)
236
+ res.setHeader('ETag', etag)
237
+
238
+ // set content-type
239
+ if (!res.getHeader('Content-Type')) {
240
+ if (opts.contentType) {
241
+ res.setHeader('Content-Type', opts.contentType)
242
+ } else {
243
+ var type = mime.lookup(pathname)
244
+ if (type) {
245
+ var charset = mime.charsets.lookup(type)
246
+ if (charset)
247
+ res.setHeader('Content-Type', type + '; charset=' + charset)
248
+ else
249
+ res.setHeader('Content-Type', type)
250
+ }
251
+ }
252
+ }
253
+
254
+ // Conditionnal GET
255
+ if (hasCondition(req.headers)) {
256
+ if (!conditionMatch(req.headers, res.getHeaders())) {
257
+ return HTTP.PRECONDITION_FAILS(res)
258
+ }
259
+
260
+ if (isCacheFresh(req.headers, res.getHeaders())) {
261
+ removeContentHeaders(res);
262
+ return HTTP.NOT_MODIFIED(res);
263
+ }
264
+ }
265
+
266
+
267
+ // Send data
268
+ res.setHeader('Content-Length', len)
269
+ if (req.method === 'HEAD')
270
+ return res.end()
271
+
272
+ let finished = false
273
+ const stream = fs.createReadStream(pathname);
274
+ res.on('finish', _ => {
275
+ finished = true;
276
+ destroyReadStream(stream);
277
+ });
278
+ stream.on('error', err => {
279
+ if (finished) return;
280
+ console.log('ERROR', pathname, err)
281
+ HTTP.INTERNAL_ERROR(res, err.code);
282
+ finished = true;
283
+ destroyReadStream(stream);
284
+ });
285
+ stream.on('end', _ => {
286
+ res.end();
287
+ });
288
+ stream.pipe(res);
289
+ }
290
+
291
+ function sendIndex(req, res, pathname, stat, opts) {
292
+
293
+ var p = path.join(pathname, 'index.html')
294
+ fs.stat(p, function (err, stat) {
295
+ if (err) {
296
+ if (err.code == 'ENOENT' || err.code == 'ENAMETOOLONG' || err.code == 'ENOTDIR') {
297
+ if (opts.fallthrough)
298
+ return next();
299
+ return HTTP.NOT_FOUND(res)
300
+ }
301
+ return HTTP.INTERNAL_ERROR(res, err.code);
302
+ }
303
+
304
+ // index file support
305
+ if (stat.isDirectory()) {
306
+ return HTTP.NOT_FOUND(res);
307
+ }
308
+
309
+ sendFile(req, res, p, stat, opts)
310
+ })
311
+ }
312
+
313
+ function serveStatic (root, options) {
314
+
315
+ if (!root)
316
+ throw new TypeError('root path required')
317
+ else if (typeof root !== 'string')
318
+ throw new TypeError('root path must be a string')
319
+
320
+ // copy options
321
+ var opts = options || {
322
+ fallthrough: false,
323
+ redirect: false,
324
+ };
325
+ opts.fallthrough = opts.fallthrough !== false
326
+ opts.redirect = opts.redirect !== false
327
+ opts.maxage = opts.maxage || opts.maxAge || 0
328
+ opts.root = path.resolve(root)
329
+ if (opts.setHeaders && typeof opts.setHeaders !== 'function')
330
+ throw new TypeError('option setHeaders must be function')
331
+
332
+
333
+ return function serveStatic (req, res, next) {
334
+
335
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
336
+ if (opts.fallthrough)
337
+ return next()
338
+ return HTTP.NOT_ALLOWED(res);
339
+ }
340
+
341
+ var originalUrl = decodeURIComponent(req.originalUrl || req.path || req.url)
342
+ var pathname = originalUrl
343
+
344
+ // make sure redirect occurs at mount
345
+ if (pathname === '/' && originalUrl.substr(-1) !== '/') {
346
+ pathname = ''
347
+ }
348
+
349
+ if (UP_PATH_REGEXP.test(pathname))
350
+ return HTTP.FORBIDDEN(res);
351
+
352
+ // resolve the path
353
+ pathname = path.resolve(path.normalize(opts.root + '/' + pathname));
354
+
355
+ // dotfile handling
356
+ if (opts.dotfiles != 'allow' && pathname.indexOf('/.') >= 0) {
357
+ if (opts.dotfiles == 'deny')
358
+ return HTTP.FORBIDDEN(res);
359
+ return HTTP.NOT_FOUND(res);
360
+ }
361
+
362
+ fs.stat(pathname, function onstat (err, stat) {
363
+ if (err) {
364
+ // console.log('DBG', pathname, err.code, req.originalUrl, req.url, req.path)
365
+ if (err.code == 'ENOENT' || err.code == 'ENAMETOOLONG' || err.code == 'ENOTDIR') {
366
+ if (opts.fallthrough)
367
+ return next();
368
+ return HTTP.NOT_FOUND(res)
369
+ }
370
+ return HTTP.INTERNAL_ERROR(res, err.code);
371
+ }
372
+
373
+ // index file support
374
+ if (stat.isDirectory()) {
375
+ // if (!opts.redirect)
376
+ // return HTTP.NOT_FOUND(res);
377
+ return sendIndex(req, res, pathname, stat, opts)
378
+ }
379
+
380
+
381
+ sendFile(req, res, pathname, stat, opts)
382
+ });
383
+ }
384
+ }
385
+
386
+
387
+
388
+ module.exports = serveStatic;