Logo

dev-resources.site

for different kinds of informations.

Serve Static File with Koa✨

Published at
6/19/2020
Categories
javascript
node
koa
koajs
Author
Imed Jaberi
Categories
4 categories in total
javascript
open
node
open
koa
open
koajs
open
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

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;

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

Featured ones: