What is koa-static?
The koa-static package is a middleware for Koa, a popular Node.js web framework. It serves static files such as HTML, CSS, JavaScript, and images from a specified directory. This is useful for serving front-end assets in a web application.
What are koa-static's main functionalities?
Serve Static Files
This feature allows you to serve static files from a specified directory. In this example, files from the 'public' directory will be served.
const Koa = require('koa');
const serve = require('koa-static');
const app = new Koa();
// Serve files from the 'public' directory
app.use(serve('./public'));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Custom Options
This feature allows you to customize the behavior of the static file serving. You can set options like cache duration, serving hidden files, and specifying a default file.
const Koa = require('koa');
const serve = require('koa-static');
const app = new Koa();
// Serve files from the 'public' directory with custom options
app.use(serve('./public', {
maxage: 86400000, // Cache files for 1 day
hidden: true, // Allow hidden files to be served
index: 'index.html' // Default file to serve
}));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Other packages similar to koa-static
serve-static
The serve-static package is a middleware for Express, another popular Node.js web framework. It serves static files similarly to koa-static but is designed for use with Express. It offers similar functionalities such as serving files from a directory and customizing options like cache control.
static-server
The static-server package is a simple, standalone HTTP server for serving static files. Unlike koa-static, it is not a middleware and does not require a web framework like Koa or Express. It is useful for quickly serving static files without setting up a full web server.
http-server
The http-server package is a simple, zero-configuration command-line HTTP server. It is used to serve static files and is often used for development and testing purposes. Unlike koa-static, it is not a middleware and does not integrate with web frameworks.
koa-static
Static file serving middleware.
Installation
$ npm install koa-static
Options
maxAge
Browser cache maxAge in milliseconds. defaults to 0hidden
Allow transfer of hidden files. defaults to falseindex
Default file name, defaults to 'index.html'
Example
var serve = require('./');
var koa = require('koa');
var app = koa();
app.use(serve('.'));
app.use(serve('test/fixtures'));
app.use(serve(__dirname + '/test/fixtures'));
app.listen(3000);
console.log('listening on port 3000');
License
MIT