Skip to content

Instantly share code, notes, and snippets.

@lucasdamianjohnson
Created May 16, 2023 19:47
Show Gist options
  • Save lucasdamianjohnson/346be1539267424b78a4da5bf2f4e5b9 to your computer and use it in GitHub Desktop.
Save lucasdamianjohnson/346be1539267424b78a4da5bf2f4e5b9 to your computer and use it in GitHub Desktop.
node server for SAB
import http from "http";
import fs from "fs/promises";
const host = "localhost";
const port = 8000;
const getFile = async (path: string) => {
try {
return await fs.readFile(`./public/${path}`);
} catch (e) {
return new Uint8Array(1);
}
};
const server = http.createServer(async function (req, res) {
if (req.url == "/") {
const indexFile = await getFile("index.html");
res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
res.writeHead(200);
return res.end(indexFile);
}
const fileExtension = req.url!.split(".").pop()!;
const indexFile = await getFile(req.url!);
let contentType = "";
switch (fileExtension) {
case "js":
contentType = "text/javascript";
break;
case "css":
contentType = "text/css";
break;
case "json":
contentType = "application/json";
break;
case "png":
contentType = "image/png";
break;
case "jpg":
contentType = "image/jpg";
break;
case "wav":
contentType = "audio/wav";
break;
}
res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
res.writeHead(200, {
"Content-Type": contentType,
});
return res.end(indexFile);
});
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment