Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hagevvashi/2834752958c4a08dd6a30379225bb31a to your computer and use it in GitHub Desktop.
Save hagevvashi/2834752958c4a08dd6a30379225bb31a to your computer and use it in GitHub Desktop.
コンテンツサーバの実装
async function contentServer(filePath: string, req: any, res: any) {
try {
const data = await fs.promises.readFile(`${filePath}`, "utf-8");
const extname = String(path.extname(filePath)).toLowerCase();
const mimeTypes = {
".html": "text/html",
".md": "text/markdown",
".js": "text/javascript",
// .tsと.tsxはプロジェクトのソースを参照したい時に備えて
".ts": "text/plain",
".tsx": "text/plain",
".css": "text/css",
".json": "application/json",
".png": "image/png",
".jpg": "image/jpg",
".gif": "image/gif",
".wav": "audio/wav",
".mp4": "video/mp4",
".woff": "application/font-woff",
".ttf": "application/font-ttf",
".eot": "application/vnd.ms-fontobject",
".otf": "application/font-otf",
".svg": "application/image/svg+xml",
} as Record<string, string>;
const contentType = mimeTypes[extname] ?? "application/octet-stream";
res.writeHead(200, { "Content-Type": `${contentType};charset=utf-8` });
res.write(data);
} catch (e) {
res.writeHead(404);
res.write(JSON.stringify(e));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment