Serve Directory Listings in an Express App with serve-index

John Au-Yeung
The Startup
Published in
5 min readFeb 23, 2020

--

Photo by Kelly Sikkema on Unsplash

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. The filter function is called on each file. It has the signature filter(filename, index, files, dir) where filename is the name of the file, index is the array index, files is the array of the files, and dir is the absolute path the file is located.

--

--