Serving Static Files

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:

Image maxAge: The browser cache maxAge, in milliseconds. Defaults to 0.

Image hidden: A Boolean that, when true, indicates that transfer of hidden files is enabled. Defaults to false.

Image 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.

Image 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.

Listing 19.1 express_static.js: Express code that implements two static routes


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);


Listing 19.2 ./static/index.html: A static HTML file that requests the CSS and image files from the server


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>


Listing 19.3 ./static/css/static.css: A CSS file that formats the images


01 img
02 {
03     display:inline;
04     margin:3px;
05     border:5px solid #000000;
06 }


Image

Figure 19.1 HTML, CSS, and image files served statically to a browser.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.126.122