📅  最后修改于: 2023-12-03 15:14:57.655000             🧑  作者: Mango
express.static
is a built-in middleware function in the Express.js framework for serving static files such as images, CSS files, and JavaScript files. It is based on the core Node.js module path
and is used to define a static directory that contains these files.
To use express.static
, you should first have an instance of an Express application created using express()
. You can then use the middleware function by calling app.use()
and passing the desired path and options.
Here's an example of how to use express.static
:
const express = require('express');
const app = express();
// Serve static files from the "public" directory
app.use(express.static('public'));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, the public
directory contains the static files you want to serve. The middleware function express.static
is used to specify that any requests for static files should be served from this directory.
express.static
also provides options that can be passed as the second parameter of the app.use()
function. Some commonly used options include:
dotfiles
: This option determines how dotfiles (files starting with a dot) are treated. Possible values are "allow"
, "deny"
, "ignore"
. The default value is "ignore"
.etag
: This option enables or disables the generation of ETags (Entity Tags) for the files. The default value is true
.lastModified
: This option enables or disables sending the Last-Modified
header for the files. The default value is true
.maxAge
: This option sets the maximum age (in milliseconds) for the cache-control max-age
directive. The default value is 0
.Here's an example showing how to use some options:
app.use(express.static('public', { dotfiles: 'ignore', etag: false, maxAge: 604800000 }));
express.static
is a powerful middleware function in Express.js, allowing you to easily serve static files. It saves you from writing repetitive code and provides various options to customize the behavior according to your needs. By using express.static
, you can efficiently handle static assets and improve the performance and scalability of your web application.