- Notifications
You must be signed in to change notification settings - Fork235
expressjs/serve-static
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
This is aNode.js module available through thenpm registry. Installation is done using thenpm install
command:
$ npm install serve-static
varserveStatic=require('serve-static')
Create a new middleware function to serve files from within a given rootdirectory. The file to serve will be determined by combiningreq.url
with the provided root directory. When a file is not found, instead ofsending a 404 response, this module will instead callnext()
to move onto the next middleware, allowing for stacking and fall-backs.
Enable or disable accepting ranged requests, defaults to true.Disabling this will not sendAccept-Ranges
and ignore the contentsof theRange
request header.
Enable or disable settingCache-Control
response header, defaults totrue. Disabling this will ignore theimmutable
andmaxAge
options.
Set how "dotfiles" are treated when encountered. A dotfile is a fileor directory that begins with a dot ("."). Note this check is done onthe path itself without checking if the path actually exists on thedisk. Ifroot
is specified, only the dotfiles above the root arechecked (i.e. the root itself can be within a dotfile when setto "deny").
'allow'
No special treatment for dotfiles.'deny'
Deny a request for a dotfile and 403/next()
.'ignore'
Pretend like the dotfile does not exist and 404/next()
.
The default value is'ignore'
.
Enable or disable etag generation, defaults to true.
Set file extension fallbacks. When set, if a file is not found, the givenextensions will be added to the file name and search for. The first thatexists will be served. Example:['html', 'htm']
.
The default value isfalse
.
Set the middleware to have client errors fall-through as just unhandledrequests, otherwise forward a client error. The difference is that clienterrors like a bad request or a request to a non-existent file will causethis middleware to simplynext()
to your next middleware when this valueistrue
. When this value isfalse
, these errors (even 404s), will invokenext(err)
.
Typicallytrue
is desired such that multiple physical directories can bemapped to the same web address or for routes to fill in non-existent files.
The valuefalse
can be used if this middleware is mounted at a path thatis designed to be strictly a single file system directory, which allows forshort-circuiting 404s for less overhead. This middleware will also reply toall methods.
The default value istrue
.
Enable or disable theimmutable
directive in theCache-Control
responseheader, defaults tofalse
. If set totrue
, themaxAge
option shouldalso be specified to enable caching. Theimmutable
directive will preventsupported clients from making conditional requests during the life of themaxAge
option to check if the file has changed.
By default this module will send "index.html" files in response to a requeston a directory. To disable this setfalse
or to supply a new index pass astring or an array in preferred order.
Enable or disableLast-Modified
header, defaults to true. Uses the filesystem's last modified value.
Provide a max-age in milliseconds for http caching, defaults to 0. Thiscan also be a string accepted by themsmodule.
Redirect to trailing "/" when the pathname is a dir. Defaults totrue
.
Function to set custom headers on response. Alterations to the headers need tooccur synchronously. The function is called asfn(res, path, stat)
, wherethe arguments are:
res
the response objectpath
the file path that is being sentstat
the stat object of the file that is being sent
varfinalhandler=require('finalhandler')varhttp=require('http')varserveStatic=require('serve-static')// Serve up public/ftp foldervarserve=serveStatic('public/ftp',{index:['index.html','index.htm']})// Create servervarserver=http.createServer(functiononRequest(req,res){serve(req,res,finalhandler(req,res))})// Listenserver.listen(3000)
varcontentDisposition=require('content-disposition')varfinalhandler=require('finalhandler')varhttp=require('http')varserveStatic=require('serve-static')// Serve up public/ftp foldervarserve=serveStatic('public/ftp',{index:false,setHeaders:setHeaders})// Set header to force downloadfunctionsetHeaders(res,path){res.setHeader('Content-Disposition',contentDisposition(path))}// Create servervarserver=http.createServer(functiononRequest(req,res){serve(req,res,finalhandler(req,res))})// Listenserver.listen(3000)
This is a simple example of using Express.
varexpress=require('express')varserveStatic=require('serve-static')varapp=express()app.use(serveStatic('public/ftp',{index:['default.html','default.htm']}))app.listen(3000)
This example shows a simple way to search through multiple directories.Files are searched for inpublic-optimized/
first, thenpublic/
secondas a fallback.
varexpress=require('express')varpath=require('path')varserveStatic=require('serve-static')varapp=express()app.use(serveStatic(path.join(__dirname,'public-optimized')))app.use(serveStatic(path.join(__dirname,'public')))app.listen(3000)
This example shows how to set a different max age depending on the servedfile. In this example, HTML files are not cached, while everything elseis for 1 day.
varexpress=require('express')varpath=require('path')varserveStatic=require('serve-static')varapp=express()app.use(serveStatic(path.join(__dirname,'public'),{maxAge:'1d',setHeaders:setCustomCacheControl}))app.listen(3000)functionsetCustomCacheControl(res,file){if(path.extname(file)==='.html'){// Custom Cache-Control for HTML filesres.setHeader('Cache-Control','public, max-age=0')}}
About
Serve static files