What is serve-static?
The serve-static npm package is used to serve static files such as images, CSS files, and JavaScript files. It is built on top of the core 'http' module in Node.js and provides a middleware that can be used with frameworks like Express to serve files from a directory in the file system.
What are serve-static's main functionalities?
Basic static file serving
This code sample demonstrates how to serve static files from a directory named 'public'. When a request is made to the server, it will look for files in this directory to serve.
const express = require('express');
const serveStatic = require('serve-static');
const app = express();
app.use(serveStatic('public'));
app.listen(3000);
Customizing cache control
This code sample shows how to customize cache control headers for the files served. The 'maxAge' option sets the cache control max-age directive in seconds, and the 'setHeaders' function allows for further customization of the headers.
const express = require('express');
const serveStatic = require('serve-static');
const app = express();
app.use(serveStatic('public', {
maxAge: '1d',
setHeaders: function (res, path) {
res.setHeader('Cache-Control', 'public, max-age=86400')
}
}));
app.listen(3000);
Serving files from multiple directories
This code sample demonstrates how to serve static files from multiple directories. The first 'serveStatic' serves files from the 'public' directory, while the second one serves files from the 'media' directory under the '/media' path.
const express = require('express');
const serveStatic = require('serve-static');
const app = express();
app.use(serveStatic('public'));
app.use('/media', serveStatic('media'));
app.listen(3000);
Other packages similar to serve-static
express-static
express-static is similar to serve-static but is specifically tailored for use with the Express framework. It provides a simpler API for serving static files in an Express application.
koa-static
koa-static is designed for the Koa framework, which is a different Node.js web framework. It provides similar functionality to serve-static but is built to work within Koa's middleware system.
connect-static
connect-static is a middleware for the Connect framework, which is a middleware layer for Node.js that can be used independently or with Express. It offers similar static file serving capabilities as serve-static.
serve-static
Install
$ npm install serve-static
API
var serveStatic = require('serve-static')
serveStatic(root, options)
Create a new middleware function to serve files from within a given root
directory. The file to serve will be determined by combining req.url
with the provided root directory. When a file is not found, instead of
sending a 404 response, this module will instead call next()
to move on
to the next middleware, allowing for stacking and fall-backs.
Options
dotfiles
Set how "dotfiles" are treated when encountered. A dotfile is a file
or directory that begins with a dot ("."). Note this check is done on
the path itself without checking if the path actually exists on the
disk. If root
is specified, only the dotfiles above the root are
checked (i.e. the root itself can be within a dotfile when set
to "deny").
The default value is 'ignore'
.
'allow'
No special treatment for dotfiles.'deny'
Send a 403 for any request for a dotfile.'ignore'
Pretend like the dotfile does not exist and call next()
.
etag
Enable or disable etag generation, defaults to true.
extensions
Set file extension fallbacks. When set, if a file is not found, the given
extensions will be added to the file name and search for. The first that
exists will be served. Example: ['html', 'htm']
.
The default value is false
.
index
By default this module will send "index.html" files in response to a request
on a directory. To disable this set false
or to supply a new index pass a
string or an array in preferred order.
lastModified
Enable or disable Last-Modified
header, defaults to true. Uses the file
system's last modified value.
maxAge
Provide a max-age in milliseconds for http caching, defaults to 0. This
can also be a string accepted by the ms
module.
redirect
Redirect to trailing "/" when the pathname is a dir. Defaults to true
.
Function to set custom headers on response. Alterations to the headers need to
occur synchronously. The function is called as fn(res, path, stat)
, where
the arguments are:
res
the response objectpath
the file path that is being sentstat
the stat object of the file that is being sent
Examples
Serve files with vanilla node.js http server
var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')
var serve = serveStatic('public/ftp', {'index': ['index.html', 'index.htm']})
var server = http.createServer(function(req, res){
var done = finalhandler(req, res)
serve(req, res, done)
})
server.listen(3000)
Serve all files as downloads
var contentDisposition = require('content-disposition')
var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')
var serve = serveStatic('public/ftp', {
'index': false,
'setHeaders': setHeaders
})
function setHeaders(res, path) {
res.setHeader('Content-Disposition', contentDisposition(path))
}
var server = http.createServer(function(req, res){
var done = finalhandler(req, res)
serve(req, res, done)
})
server.listen(3000)
Serving using express
var connect = require('connect')
var serveStatic = require('serve-static')
var app = connect()
app.use(serveStatic('public/ftp', {'index': ['default.html', 'default.htm']}))
app.listen(3000)
License
MIT