1
0

server.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import http from 'http';
  2. import path from 'path';
  3. import os from 'os';
  4. import { createReadStream, existsSync, statSync, readdirSync } from 'fs';
  5. import { fileURLToPath } from 'url';
  6. function escapeHtml( str ) {
  7. return str
  8. .replace( /&/g, '&' )
  9. .replace( /</g, '&lt;' )
  10. .replace( />/g, '&gt;' )
  11. .replace( /"/g, '&quot;' );
  12. }
  13. const mimeTypes = {
  14. '.html': 'text/html',
  15. '.js': 'application/javascript',
  16. '.css': 'text/css',
  17. '.json': 'application/json',
  18. '.png': 'image/png',
  19. '.jpg': 'image/jpeg',
  20. '.gif': 'image/gif',
  21. '.svg': 'image/svg+xml',
  22. '.mp3': 'audio/mpeg',
  23. '.mp4': 'video/mp4',
  24. '.webm': 'video/webm',
  25. '.ogv': 'video/ogg',
  26. '.ogg': 'audio/ogg',
  27. '.woff': 'font/woff',
  28. '.woff2': 'font/woff2',
  29. '.ttf': 'font/ttf',
  30. '.glb': 'model/gltf-binary',
  31. '.gltf': 'model/gltf+json',
  32. '.hdr': 'application/octet-stream',
  33. '.exr': 'application/octet-stream',
  34. '.fbx': 'application/octet-stream',
  35. '.bin': 'application/octet-stream',
  36. '.cube': 'text/plain',
  37. '.wasm': 'application/wasm',
  38. '.ktx2': 'image/ktx2'
  39. };
  40. function createHandler( rootDirectory ) {
  41. return ( req, res ) => {
  42. const pathname = decodeURIComponent( req.url.split( '?' )[ 0 ] );
  43. let filePath = path.join( rootDirectory, pathname );
  44. // Prevent path traversal attacks
  45. if ( ! filePath.startsWith( rootDirectory ) ) {
  46. res.writeHead( 403 );
  47. res.end( 'Forbidden' );
  48. return;
  49. }
  50. // Handle directories
  51. if ( existsSync( filePath ) && statSync( filePath ).isDirectory() ) {
  52. const indexPath = path.join( filePath, 'index.html' );
  53. if ( existsSync( indexPath ) ) {
  54. filePath = indexPath;
  55. } else {
  56. // Show directory listing
  57. const files = readdirSync( filePath )
  58. .filter( f => ! f.startsWith( '.' ) )
  59. .map( f => ( { name: f, isDir: statSync( path.join( filePath, f ) ).isDirectory() } ) )
  60. .sort( ( a, b ) => {
  61. if ( a.isDir && ! b.isDir ) return - 1;
  62. if ( ! a.isDir && b.isDir ) return 1;
  63. return a.name.localeCompare( b.name );
  64. } );
  65. const base = pathname.endsWith( '/' ) ? pathname : pathname + '/';
  66. const items = files.map( ( { name, isDir } ) => {
  67. const safeFile = escapeHtml( name );
  68. const safeHref = escapeHtml( base + name + ( isDir ? '/' : '' ) );
  69. const icon = isDir ? '📁' : '📄';
  70. return `<a href="${safeHref}"><span class="i">${icon}</span>${safeFile}</a>`;
  71. } ).join( '\n' );
  72. const safePath = escapeHtml( pathname );
  73. const html = `<!DOCTYPE html>
  74. <html>
  75. <head>
  76. <meta charset="utf-8">
  77. <meta name="viewport" content="width=device-width">
  78. <meta name="color-scheme" content="light dark">
  79. <title>Index of ${safePath}</title>
  80. <style>
  81. body { font-family: system-ui, sans-serif; margin: 20px; }
  82. h1 { font-weight: normal; font-size: 1.2em; margin-bottom: 10px; }
  83. a { display: block; padding: 6px 8px; color: inherit; text-decoration: none; border-radius: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  84. a:hover { background: rgba(128,128,128,0.2); }
  85. .i { display: inline-block; width: 1.5em; }
  86. </style>
  87. </head>
  88. <body>
  89. <h1>Index of ${safePath}</h1>
  90. ${pathname !== '/' ? '<a href="../"><span class="i">📁</span>..</a>' : ''}
  91. ${items}
  92. </body>
  93. </html>`;
  94. res.writeHead( 200, { 'Content-Type': 'text/html' } );
  95. res.end( html );
  96. return;
  97. }
  98. }
  99. if ( ! existsSync( filePath ) ) {
  100. res.writeHead( 404 );
  101. res.end( 'File not found' );
  102. return;
  103. }
  104. const ext = path.extname( filePath ).toLowerCase();
  105. const contentType = mimeTypes[ ext ] || 'application/octet-stream';
  106. const stat = statSync( filePath );
  107. const fileSize = stat.size;
  108. const range = req.headers.range;
  109. if ( range ) {
  110. const parts = range.replace( /bytes=/, '' ).split( '-' );
  111. const start = parseInt( parts[ 0 ], 10 );
  112. const end = parts[ 1 ] ? parseInt( parts[ 1 ], 10 ) : fileSize - 1;
  113. res.writeHead( 206, {
  114. 'Content-Range': `bytes ${start}-${end}/${fileSize}`,
  115. 'Accept-Ranges': 'bytes',
  116. 'Content-Length': end - start + 1,
  117. 'Content-Type': contentType
  118. } );
  119. createReadStream( filePath, { start, end } ).pipe( res );
  120. } else {
  121. res.writeHead( 200, {
  122. 'Content-Length': fileSize,
  123. 'Content-Type': contentType
  124. } );
  125. createReadStream( filePath ).pipe( res );
  126. }
  127. };
  128. }
  129. export function createServer( options = {} ) {
  130. const rootDirectory = options.root || path.resolve();
  131. const handler = createHandler( rootDirectory );
  132. return http.createServer( handler );
  133. }
  134. function tryListen( server, port, maxAttempts = 20 ) {
  135. return new Promise( ( resolve, reject ) => {
  136. let attempts = 0;
  137. const onError = ( err ) => {
  138. if ( err.code === 'EADDRINUSE' && attempts < maxAttempts ) {
  139. attempts ++;
  140. server.listen( port + attempts );
  141. } else {
  142. reject( err );
  143. }
  144. };
  145. const onListening = () => {
  146. server.off( 'error', onError );
  147. resolve( server.address().port );
  148. };
  149. server.once( 'error', onError );
  150. server.once( 'listening', onListening );
  151. server.listen( port );
  152. } );
  153. }
  154. // CLI mode
  155. const isMain = process.argv[ 1 ] && path.resolve( process.argv[ 1 ] ) === path.resolve( fileURLToPath( import.meta.url ) );
  156. if ( isMain ) {
  157. const args = process.argv.slice( 2 );
  158. const requestedPort = parseInt( args.find( ( _, i, arr ) => arr[ i - 1 ] === '-p' ) || '8080', 10 );
  159. const rootDirectory = path.resolve();
  160. const handler = createHandler( rootDirectory );
  161. const server = http.createServer( handler );
  162. const port = await tryListen( server, requestedPort );
  163. if ( port !== requestedPort ) {
  164. console.log( `\x1b[33mPort ${requestedPort} in use, using ${port} instead.\x1b[0m` );
  165. }
  166. console.log( `\x1b[32mServer running at http://localhost:${port}/\x1b[0m` );
  167. // Show network addresses
  168. const interfaces = os.networkInterfaces();
  169. for ( const name of Object.keys( interfaces ) ) {
  170. for ( const net of interfaces[ name ] ) {
  171. if ( net.family === 'IPv4' && ! net.internal ) {
  172. console.log( ` http://${net.address}:${port}/` );
  173. }
  174. }
  175. }
  176. console.log( '\nPress Ctrl+C to stop.' );
  177. process.on( 'SIGINT', () => {
  178. console.log( '\nShutting down...' );
  179. server.close();
  180. process.exit( 0 );
  181. } );
  182. }
粤ICP备19079148号