DEV Community

loading...

Serve Static File with Koa✨

3imed_jaberi profile image Imed Jaberi ・1 min read

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 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;

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

Discussion (0)

pic
Editor guide