server.js 6.0 KB

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