Created
September 26, 2018 20:21
-
-
Save lap00zza/ed0beb9809bc3d7cb1e6802cd3981bf3 to your computer and use it in GitHub Desktop.
Easily serve all your static files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require("http"); | |
const fs = require("fs"); | |
const path = require("path"); | |
const util = require("util"); | |
const PORT = process.argv[2] || 8080; | |
const __cwd = process.cwd(); | |
const _access = util.promisify(fs.access); | |
const _readdir = util.promisify(fs.readdir); | |
const reqListener = async (req, res) => { | |
console.log(req.url); | |
const fp = path.join(__cwd, req.url); | |
try { | |
// If file does not exist we skill to catch block. | |
await _access(fp, fs.constants.F_OK); | |
// If path is a directory, we show directory listing. | |
// TODO: The only exception is the root directory, in which | |
// index.html will be tried first before falling back | |
// to directory list. | |
if (fs.statSync(fp).isDirectory()) { | |
let files = await _readdir(fp); | |
let d_listing = "<pre>"; | |
d_listing += `<a href="../">../</a>\n`; | |
files.forEach(file => { | |
try { | |
fs.statSync(path.join(fp, file)).isDirectory() | |
? d_listing += `<a href="${file}/">${file}/</a>` | |
: d_listing += `<a href="${file}">${file}</a>`; | |
} catch (e) { | |
console.error(e.message); | |
d_listing += `<a href="${file}">${file}</a>`; | |
} | |
d_listing += "\n"; | |
}); | |
d_listing += "</pre>"; | |
res.writeHead(200, { | |
"Content-Type": "text/html" | |
}); | |
return res.end(d_listing); | |
} else { | |
const readable = fs.createReadStream(fp); | |
res.writeHead(200, { | |
"Content-Length": fs.statSync(fp).size, | |
}); | |
readable.pipe(res); | |
} | |
} catch (e) { | |
console.log(e); | |
res.writeHead(404); | |
res.end(":("); | |
} | |
}; | |
const server = http.createServer(reqListener); | |
server.listen(PORT, () => { | |
console.log(`Serving on http://localhost:${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment