@@ -47,6 +47,30 @@ function list(dir, fn, pre='') {
47
47
}
48
48
}
49
49
50
+ function send ( req , res , file , stats , headers = { } ) {
51
+ let code = 200 , opts = { } ;
52
+
53
+ if ( req . headers . range ) {
54
+ code = 206 ;
55
+ let [ x , y ] = req . headers . range . replace ( 'bytes=' , '' ) . split ( '-' ) ;
56
+ let end = opts . end = parseInt ( y , 10 ) || stats . size - 1 ;
57
+ let start = opts . start = parseInt ( x , 10 ) || 0 ;
58
+
59
+ if ( start >= stats . size || end >= stats . size ) {
60
+ res . setHeader ( 'Content-Range' , `bytes */${ stats . size } ` ) ;
61
+ res . statusCode = 416 ;
62
+ return res . end ( ) ;
63
+ }
64
+
65
+ headers [ 'Content-Range' ] = `bytes ${ start } -${ end } /${ stats . size } ` ;
66
+ headers [ 'Content-Length' ] = ( end - start + 1 ) ;
67
+ headers [ 'Accept-Ranges' ] = 'bytes' ;
68
+ }
69
+
70
+ res . writeHead ( code , headers ) ;
71
+ fs . createReadStream ( file , opts ) . pipe ( res ) ;
72
+ }
73
+
50
74
module . exports = function ( dir , opts = { } ) {
51
75
dir = resolve ( dir || '.' ) ;
52
76
@@ -55,12 +79,18 @@ module.exports = function (dir, opts={}) {
55
79
56
80
if ( opts . dev ) {
57
81
return function ( req , res , next ) {
82
+ let [ start = 0 , end = Infinity ] = ( req . headers . range || '' ) . replace ( 'bytes=' , '' ) . split ( '-' ) ;
58
83
let uri = decodeURIComponent ( req . path || req . pathname || parser ( req ) . pathname ) ;
59
84
let arr = uri . includes ( '.' ) ? [ uri ] : toAssume ( uri , extensions ) ;
60
85
let file = arr . map ( x => join ( dir , x ) ) . find ( fs . existsSync ) ;
61
86
if ( ! file ) return next ? next ( ) : isNotFound ( res ) ;
62
- res . setHeader ( 'Content-Type' , mime . getType ( file ) ) ;
63
- fs . createReadStream ( file ) . pipe ( res ) ;
87
+
88
+ let stats = fs . statSync ( file ) ;
89
+ send ( req , res , file , stats , {
90
+ 'Content-Type' : mime . getType ( file ) ,
91
+ 'Last-Modified' : stats . mtime . toUTCString ( ) ,
92
+ 'Content-Length' : stats . size ,
93
+ } ) ;
64
94
}
65
95
}
66
96
@@ -91,8 +121,6 @@ module.exports = function (dir, opts={}) {
91
121
if ( ! data ) return next ? next ( ) : isNotFound ( res ) ;
92
122
93
123
setHeaders ( res , pathname , data . stats ) ;
94
- res . writeHead ( 200 , data . headers ) ;
95
-
96
- fs . createReadStream ( data . abs ) . pipe ( res ) ;
124
+ send ( req , res , data . abs , data . stats , data . headers ) ;
97
125
} ;
98
126
}
0 commit comments