import http from "http"; import { readdir } from "fs/promises"; import { stat } from "fs/promises"; import { readFile } from "fs/promises"; import { join } from "path"; import { dirname } from "path"; import { fileURLToPath } from "url"; class App { constructor( ) { const selfPath = fileURLToPath( import.meta.url ); this.rootPath = dirname( selfPath ); this.httpServer = null; } async start( ) { this.httpServer = http.createServer( this.handleRequest.bind( this ) ); this.httpServer.listen( 3000 ); } async handleRequest( req, res ) { const requestedPath = decodeURI( req.url ); const fullPath = join( this.rootPath, requestedPath ); const exists = await this.checkFileExists( fullPath ); if ( !exists ) { res.statusCode = 404; res.end( "Not Found" ); return; } const stats = await stat( fullPath ); if ( stats.isDirectory( ) ) { const indexPath = join( fullPath, "index.html" ); const indexExists = await this.checkFileExists( indexPath ); if ( indexExists ) { await this.sendFile( indexPath, res ); return; } await this.sendDirectoryListing( fullPath, requestedPath, res ); return; } await this.sendFile( fullPath, res ); } async sendFile( path, res ) { const contentType = this.getContentType( path ); const fileData = await readFile( path ); res.setHeader( "Content-Type", contentType ); res.statusCode = 200; res.end( fileData ); } async sendDirectoryListing( dirPath, urlPath, res ) { const entries = await readdir( dirPath, { withFileTypes : true } ); let html = "