Serving Static Files
Read a file and send it with the right content type. Never trust paths from users.
Example
const http = require("http"), fs = require("fs"), path = require("path"), os = require("os");
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "s-"));
fs.writeFileSync(path.join(dir, "index.html"), "<h1>Hi</h1>");
const s = http.createServer((req, res) => {
const f = path.join(dir, path.basename(req.url === "/" ? "index.html" : req.url));
fs.readFile(f, (e, d) => { if (e) { res.statusCode = 404; return res.end("no"); } res.setHeader("Content-Type", "text/html"); res.end(d); });
}).listen(0, async () => {
const r = await fetch("http://localhost:" + s.address().port);
console.log(r.status, await r.text());
s.close(); fs.rmSync(dir, { recursive: true });
});Result
200 <h1>Hi</h1>
Exercise
Safe file name.
path.(req.url)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.