DEV Community

Imed Jaberi
Imed Jaberi

Posted on • Updated on

Serve Static File with Koa✨

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
Enter fullscreen mode Exit fullscreen mode

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} 🚀 ..`));
Enter fullscreen mode Exit fullscreen mode

⚠️ 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
|   └── ...
Enter fullscreen mode Exit fullscreen mode

So, you can use the following entrypoint to access these static files;

Thank you for reading ❤️. I hope, I didn't waste your time 😇.

Top comments (0)