forked from expressjs/serve-static
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
92 lines (72 loc) · 1.74 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
/*!
* serve-static
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* Copyright(c) 2014-2016 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var parseUrl = require('parseurl')
var resolve = require('path').resolve
var fs = require('fs')
/**
* Module exports.
* @public
*/
module.exports = serveStatic
/**
* @param {string} root
* @param {object} [options]
* @return {function}
* @public
*/
function serveStatic (root, opts) {
if (!root) {
throw new TypeError('root path required')
}
if (typeof root !== 'string') {
throw new TypeError('root path must be a string')
}
if(!opts) opts = {}
// fall-though
var fallthrough = opts.fallthrough !== false
// headers listener
var setHeaders = opts.setHeaders
if (setHeaders && typeof setHeaders !== 'function') {
throw new TypeError('option setHeaders must be function')
}
// setup options for send
root = resolve(root)
return function serveStatic (req, res, next) {
if (req.method !== 'GET' && req.method !== 'HEAD') {
if (fallthrough) {
return next()
}
// method not allowed
res.statusCode = 405
res.setHeader('Allow', 'GET, HEAD')
res.setHeader('Content-Length', '0')
res.end()
return
}
var originalUrl = parseUrl.original(req)
var path = parseUrl(req).pathname
// make sure redirect occurs at mount
if (path === '/' && originalUrl.pathname.substr(-1) !== '/') {
path = ''
}
var filePath = root + "/" + path
fs.access(filePath, fs.constants.R_OK, err=>{
if(err){
next()
return
}
var urlPath = opts.root + "/" + path
res.sendFile(urlPath);
})
}
}