How to serve a static file using koa?

by haylee.mertz , in category: Javascript , 6 months ago

How to serve a static file using koa?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 6 months ago

@haylee.mertz 

To serve a static file using Koa, you can use the koa-static middleware. Here's an example of how you can serve a static file:

  1. First, install the koa-static middleware package by running:
1
npm install koa-static


  1. Next, create a new Koa app and use the koa-static middleware to serve static files. Here's an example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const Koa = require('koa');
const static = require('koa-static');
const app = new Koa();

// Serve files from the 'public' directory
app.use(static(__dirname + '/public'));

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});


In this example, the koa-static middleware is used to serve static files from the 'public' directory. Any files placed in the 'public' directory will be served by Koa.

  1. Create a 'public' directory in your project and place the static files you want to serve inside it.
  2. Start your Koa server by running node server.js (assuming your server file is named 'server.js' as in the example above).


Now, when you access http://localhost:3000/{filename} in your browser, Koa will serve the static file from the 'public' directory based on the specified filename.