Skip to content
Myr

index.js

This file

Path

examples/static-files/index.js

44 lines · 1.5 KiB · JavaScript

Last changed by

add app.router to static-files exampleTJ Holowaychukbefore adoption2c174d6

History of this file

Take it

add static-files exampleTJ Holowaychukbefore adoption60ee465

lines 1–30why, one step back
1
2var express = require('../..');3var app = express();45// log requests6app.use(express.logger('dev'));78// express on its own has no notion9// of a "file". The express.static()10// middleware checks for a file matching11// the `req.path` within the directory12// that you pass it. In this case "GET /js/app.js"13// will look for "./public/js/app.js".1415app.use(express.static(__dirname + '/public'));1617// if you wanted to "prefix" you may use18// the mounting feature of Connect, for example19// "GET /static/js/app.js" instead of "GET /js/app.js".20// The mount-path "/static" is simply removed before21// passing control to the express.static() middleware,22// thus it serves the file correctly by ignoring "/static"23app.use('/static', express.static(__dirname + '/public'));2425// if for some reason you want to serve files from26// several directories, you can use express.static()27// multiple times! Here we're passing "./public/css",28// this will allow "GET /style.css" instead of "GET /css/style.css":29app.use(express.static(__dirname + '/public/css'));30

add app.router to static-files exampleTJ Holowaychukbefore adoption2c174d6

lines 31–38why, one step back
31// this examples does not have any routes, however
32// you may `app.use(app.router)` before or after these33// static() middleware. If placed before them your routes34// will be matched BEFORE file serving takes place. If placed35// after as shown here then file serving is performed BEFORE36// any routes are hit:37app.use(app.router);38

add static-files exampleTJ Holowaychukbefore adoption60ee465

lines 39–44why, one step back
39app.listen(3000);
40console.log('listening on port 3000');41console.log('try:');42console.log(' GET /hello.txt');43console.log(' GET /js/app.js');44console.log(' GET /css/style.css');