1
1
const fs = require ( 'fs' ) ;
2
2
const { join, resolve } = require ( 'path' ) ;
3
- const tglob = require ( 'tiny-glob/sync' ) ;
4
3
const parser = require ( '@polka/url' ) ;
5
4
const mime = require ( 'mime/lite' ) ;
6
5
@@ -9,7 +8,9 @@ const noop = () => {};
9
8
10
9
function toAssume ( uri , extns ) {
11
10
let i = 0 , x , len = uri . length - 1 ;
12
- if ( uri . charCodeAt ( len ) === 47 ) uri = uri . substring ( 0 , len ) ;
11
+ if ( uri . charCodeAt ( len ) === 47 ) {
12
+ uri = uri . substring ( 0 , len ) ;
13
+ }
13
14
14
15
let arr = [ ] , tmp = `${ uri } /index` ;
15
16
for ( ; i < extns . length ; i ++ ) {
@@ -30,14 +31,22 @@ function find(uri, extns) {
30
31
return data ;
31
32
}
32
33
33
- function toEtag ( obj ) {
34
- return `W/"${ obj . size . toString ( 16 ) } -${ obj . mtime . getTime ( ) . toString ( 16 ) } "` ;
35
- }
36
-
37
34
function is404 ( res ) {
38
35
return ( res . statusCode = 404 , res . end ( ) ) ;
39
36
}
40
37
38
+ function list ( dir , fn , pre = '' ) {
39
+ let i = 0 , abs , stats ;
40
+ let arr = fs . readdirSync ( dir ) ;
41
+ for ( ; i < arr . length ; i ++ ) {
42
+ abs = join ( dir , arr [ i ] ) ;
43
+ stats = fs . statSync ( abs ) ;
44
+ stats . isDirectory ( )
45
+ ? list ( abs , fn , join ( pre , arr [ i ] ) )
46
+ : fn ( join ( pre , arr [ i ] ) , abs , stats ) ;
47
+ }
48
+ }
49
+
41
50
module . exports = function ( dir , opts = { } ) {
42
51
dir = resolve ( dir || '.' ) ;
43
52
@@ -59,20 +68,21 @@ module.exports = function (dir, opts={}) {
59
68
let cc = opts . maxAge != null && `public,max-age=${ opts . maxAge } ` ;
60
69
if ( cc && opts . immutable ) cc += ',immutable' ;
61
70
62
- opts . cwd = dir ;
63
- let abs , stats , headers ;
64
- opts . dot = ! ! opts . dotfiles ;
65
- tglob ( '**/*.*' , opts ) . forEach ( str => {
66
- abs = join ( dir , str ) ;
67
- stats = fs . statSync ( abs ) ;
68
- headers = {
71
+ list ( dir , ( name , abs , stats ) => {
72
+ if ( ! opts . dotfiles && name . charAt ( 0 ) === '.' ) {
73
+ return ;
74
+ }
75
+
76
+ let headers = {
69
77
'Content-Length' : stats . size ,
70
- 'Content-Type' : mime . getType ( str ) ,
71
- 'Last-Modified' : stats . mtime . toUTCString ( )
78
+ 'Content-Type' : mime . getType ( name ) ,
79
+ 'Last-Modified' : stats . mtime . toUTCString ( ) ,
72
80
} ;
81
+
73
82
if ( cc ) headers [ 'Cache-Control' ] = cc ;
74
- if ( opts . etag ) headers [ 'ETag' ] = toEtag ( stats ) ;
75
- FILES [ '/' + str . replace ( / \\ + / g, '/' ) ] = { abs, stats, headers } ;
83
+ if ( opts . etag ) headers [ 'ETag' ] = `W/"${ stats . size } -${ stats . mtime . getTime ( ) } "` ;
84
+
85
+ FILES [ '/' + name . replace ( / \\ + / g, '/' ) ] = { abs, stats, headers } ;
76
86
} ) ;
77
87
78
88
return function ( req , res , next ) {
@@ -84,5 +94,5 @@ module.exports = function (dir, opts={}) {
84
94
res . writeHead ( 200 , data . headers ) ;
85
95
86
96
fs . createReadStream ( data . abs ) . pipe ( res ) ;
87
- }
97
+ } ;
88
98
}
0 commit comments