1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| const http = require("http") const fs = require("fs") const path = require("path")
const blockedFiles = ["secret.txt", ".exe"] const ignore = [ ".git", ".vscode", ".DS_Store", "node_modules", "package-lock.json", ".htaccess", ]
const server = http.createServer((req, res) => { const filePath = path.join(__dirname, req.url)
if (blockedFiles.some((file) => filePath.includes(file))) { res.statusCode = 403 res.end("Access to this file is forbidden") return }
fs.access(filePath, fs.constants.F_OK, (err) => { if (err) { res.statusCode = 404 res.end("File not found") return }
fs.stat(filePath, (err, stats) => { if (err) { res.statusCode = 500 res.end("Internal server error") return }
if (stats.isDirectory()) { const indexFilePath = path.join(filePath, "index.html") fs.access(indexFilePath, fs.constants.F_OK, (err) => { if (err) { fs.readdir(filePath, (err, files) => { if (err) { res.statusCode = 500 res.end("Internal server error") return }
const html = ` <html> <head> <title>Directory listing for ${req.url}</title> </head> <body> <h1>Directory listing for ${req.url}</h1> <ul> ${files .filter((item) => !ignore.includes(item)) .sort() .map( (file) => `<li><a href="${path.join( req.url, file )}">${file}</a></li>` ) .join("")} </ul> </body> </html> `
res.setHeader("Content-Type", "text/html") res.end(html) }) } else { serveFile(indexFilePath, res) } }) } else { serveFile(filePath, res) } }) }) })
function serveFile(filePath, res) { const fileStream = fs.createReadStream(filePath) fileStream.on("open", () => { res.setHeader("Content-Type", getContentType(filePath)) fileStream.pipe(res) }) fileStream.on("error", (err) => { res.statusCode = 500 res.end("Internal server error") }) }
function getContentType(filePath) { const extname = path.extname(filePath) switch (extname) { case ".html": return "text/html" case ".css": return "text/css" case ".js": return "text/javascript" case ".json": return "application/json" case ".png": return "image/png" case ".jpg": case ".jpeg": return "image/jpeg" default: return "application/octet-stream" } }
server.listen(3300, () => { console.log("Server listening on port 3300") })
|