Serve Directory Listings in an Express App with serve-index
With the serve-index
middleware, we can serve pages that contain directory listings for a given path.
In this article, we’ll look at how to use the module to serve directory listings for directories on a server.
Installation
It’s available as a Node package. We can install it by running:
npm install serve-index
Options
path
The serverIndex
function from the server-index
module takes 2 arguments, which are the path
and options
arguments and returns a middleware that servers an index of a directory of a given path.
The path
is based off the req.url
value, so req.url
of /dir
with a path
of public
will look for /public/dir
.
We can change the base URL in Express.
options
The options
object is an object that can take the following properties:
filter
— a function for files. Thefilter
function is called on each file. It has the signaturefilter(filename, index, files, dir)
wherefilename
is the name of the file,index
is the array index,files
is the array of the files, anddir
is the absolute path the file is located.