How to specify a static folder in koa?

by muriel.schmidt , in category: Javascript , 8 months ago

How to specify a static folder in koa?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , 8 months ago

@muriel.schmidt 

In Koa, you can specify a static folder by using the koa-static middleware. This middleware serves static files from a specific directory in your project.


First, install koa-static by running the following command in your project directory:

1
npm install koa-static


Then, in your Koa application, import and use the koa-static middleware like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
const Koa = require('koa');
const static = require('koa-static');
const path = require('path');

const app = new Koa();

// Specify the static folder
const staticPath = path.join(__dirname, 'public');

// Serve static files from the specified folder
app.use(static(staticPath));

// Other middleware and routes can go here

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


In this example, we specified that the static files should be served from the public folder in the current directory. You can change the staticPath variable to point to the desired folder where your static files are located. Remember that the koa-static middleware needs to be placed before any routes in order to serve static files properly.