Koa.js is a very minimal and high perf. Node.js framework. For that, it will be one of the best solution for serve static files.
Let's Start 🐣
After initializing a new project by generate new package.json
file and creating an index.js
file, we need to add koa
and koa-static
:
# npm ..
npm i koa koa-static
# yarn ..
yarn add koa koa-static
Now, we are ready to setup the Koa.js application (instance), then add koa-static as middleware:
// Modules
const Koa = require('koa');
const path = require('path');
const serve = require('koa-static');
// Expected here; serve static files from public dir
const staticDirPath = path.join(__dirname, 'public');
// Init Koa.js server
const server = new Koa();
// Mount the middleware
server.use(serve(staticDirPath));
// Run Koa.js server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server Listening on PORT ${PORT} 🚀 ..`));
⚠️ I know that it's not the only way, but it's the fastest.
Example 👾
Let's say the folder we expected to use contains these files;
├── public/
| ├── test.html
| ├── test.md
| └── test.png
| └── test.txt
| └── ...
So, you can use the following entrypoint to access these static files;
- http://localhost:3000/test.html
- http://localhost:3000/test.md
- http://localhost:3000/test.png
- http://localhost:3000/test.txt
- http://localhost:3000/...
Top comments (0)