The static
middleware is very commonly used Express middleware. The static
middleware allows you to server static files directly from disk to the client. You can use static
middleware to support things like JavaScript files, CSS files, image files, and HTML documents that do not change. The static
module is extremely easy to implement and uses the following syntax:
express.static(path, [options])
The path
parameter specifies the root path from which the static files will be referenced in the requests. The options
parameter allows you to set the following properties:
maxAge: The browser cache maxAge
, in milliseconds. Defaults to 0
.
hidden: A Boolean that, when true
, indicates that transfer of hidden files is enabled. Defaults to false
.
redirect: A Boolean that, when true
, indicates that if the request path is a directory, the request is redirected to the path with a trailing /. Defaults to true
.
index: The default filename for the root path. Defaults to index.html
.
Listings 19.1 through 19.3 show the Express code, HTML, and CSS used to implement the static
middleware to support serving static HTML, CSS, and image files. Notice that two static
paths are implemented: one for the route /
that maps to a subdirectory named static
and the second for the route /images
that maps to a peer directory named images
. Figure 19.1 shows a statically served HTML document in a web browser.
01 var express = require('express'),
02 var app = express();
03 app.use('/', express.static('./static'), {maxAge:60*60*1000});
04 app.use('/images', express.static( '../images'));
05 app.listen(80);
01 <html>
02 <head>
03 <title>Static File</title>
04 <link rel="stylesheet" type="text/css" href="css/static.css">
05 </head>
06 <body>
07 <img src="/images/arch.jpg" height="200px"/>
08 <img src="/images/flower.jpg" height="200px" />
09 <img src="/images/bison.jpg" height="200px" />
10 </body>
11 </html>
01 img
02 {
03 display:inline;
04 margin:3px;
05 border:5px solid #000000;
06 }