Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Serve static files

License

NotificationsYou must be signed in to change notification settings

expressjs/serve-static

Repository files navigation

NPM VersionNPM DownloadsCITest Coverage

Install

This is aNode.js module available through thenpm registry. Installation is done using thenpm install command:

$ npm install serve-static

API

varserveStatic=require('serve-static')

serveStatic(root, options)

Create a new middleware function to serve files from within a given rootdirectory. The file to serve will be determined by combiningreq.urlwith 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.

Options

acceptRanges

Enable or disable accepting ranged requests, defaults to true.Disabling this will not sendAccept-Ranges and ignore the contentsof theRange request header.

cacheControl

Enable or disable settingCache-Control response header, defaults totrue. Disabling this will ignore theimmutable andmaxAge options.

dotfiles

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

etag

Enable or disable etag generation, defaults to true.

extensions

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.

fallthrough

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.

immutable

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.

index

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.

lastModified

Enable or disableLast-Modified header, defaults to true. Uses the filesystem's last modified value.

maxAge

Provide a max-age in milliseconds for http caching, defaults to 0. Thiscan also be a string accepted by themsmodule.

redirect

Redirect to trailing "/" when the pathname is a dir. Defaults totrue.

setHeaders

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 object
  • path the file path that is being sent
  • stat the stat object of the file that is being sent

Examples

Serve files with vanilla node.js http server

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)

Serve all files as downloads

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)

Serving using express

Simple

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)

Multiple roots

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)

Different settings for paths

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')}}

License

MIT


[8]ページ先頭

©2009-2025 Movatter.jp