1+ const serveStatic = require ( "serve-static" ) ;
2+ const http = require ( "http" ) ;
3+ const finalhandler = require ( "finalhandler" ) ;
4+
5+ const DEFAULT_PORT = 8080 ;
6+
7+ function serve ( { acceptRanges = true , debug = false , root, port } = { acceptRanges : true } ) {
8+ if ( ! root ) {
9+ root = process . cwd ( ) ;
10+ if ( debug ) console . log ( `[srvd] root not set so using current working directory "${ root } "` ) ;
11+ }
12+
13+
14+
15+ if ( ! port ) port = process . env . SRVD_DEFAULT_PORT ? process . env . SRVD_DEFAULT_PORT : DEFAULT_PORT ;
16+ port = parseInt ( port ) ;
17+
18+ const serve = serveStatic ( root , {
19+ acceptRanges
20+ } ) ;
21+
22+ const server = http . createServer ( function onRequest ( req , res ) {
23+ serve ( req , res , finalhandler ( req , res ) ) ;
24+ } ) ;
25+
26+ server . listen ( port ) ;
27+ if ( debug ) console . log ( "[srvd] serving on port " + port ) ;
28+
29+ function checkForCloseRequest ( ) {
30+ if ( [ "TRUE" , "True" , "true" ] . includes ( process . env . SRVD_PLZ_CLOSE ) ) {
31+ server . close ( ) ;
32+ } else {
33+ setTimeout ( ( ) => checkForCloseRequest ( ) , 500 ) ;
34+ }
35+ }
36+ setTimeout ( ( ) => checkForCloseRequest ( ) , 500 ) ;
37+
38+ return { acceptRanges, debug, server, port, root } ;
39+ } ;
40+
41+ module . exports = { serve } ;
42+
43+ if ( require . main === module ) {
44+ const args = Array . from ( process . argv ) ;
45+ const str = args . join ( " " ) ;
46+ serve ( {
47+ debug : ! ! str . match ( / - ? - d e b u g ( ( = | = = ) ( t r u e | T r u e | T R U E ) ) ? / ) ,
48+ port : str . match ( / - ? - p o r t (?: = | = = ) ( \d + ) / ) ?. [ 1 ] ,
49+ root : str . match ( / - ? - r o o t (?: = | = = ) ( [ ^ ] + ) / ) ?. [ 1 ]
50+ } ) ;
51+ }
0 commit comments