Skip to content

Instantly share code, notes, and snippets.

@njfamirm
Last active December 20, 2022 06:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save njfamirm/9bcaca2b6a672e729c099193b4aafe9f to your computer and use it in GitHub Desktop.
Save njfamirm/9bcaca2b6a672e729c099193b4aafe9f to your computer and use it in GitHub Desktop.
Serving static file and favicon.ico in Oak [ Deno ]

Serving static file in Oak deno

Project layout

├── public
│   ├── favicon.ico
│   └── style.css
├── view
│   └── index.html
└── index.ts

based on Mark Tyers's answer ❤️

Of course, there is a better way to serve static files with nginx!

import { Application, Context, Router, send, Status } from "https://deno.land/x/oak/mod.ts"
// check file exist
async function checkFileExist(ctx: Context) {
const path = `${Deno.cwd()}/${ctx.request.url.pathname}`;
try {
const fileInfo = await Deno.lstat(path);
return fileInfo.isFile;
} catch {
console.log(path);
return false;
}
}
const router = new Router();
const app = new Application();
// serve home page
router.get("/", async (ctx: Context) => {
await send(ctx, "/", {
root: `${Deno.cwd()}/view`,
index: "index.html",
});
});
// serve favoicon.ico
router.get("/favicon.ico", async (ctx: Context) => {
await send(ctx, "/favicon.ico", {
root: `${Deno.cwd()}/public`,
index: "favicon.ico",
});
});
app.use(router.routes());
app.use(router.allowedMethods());
// serve static file
app.use(async (ctx, next) => {
if (await checkFileExist(ctx)) {
await send(ctx, ctx.request.url.pathname, {
root: `${Deno.cwd()}`,
});
} else {
next();
}
});
// serving on http://localhost:8000
await app.listen({ port: 8000 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment