Using a library
There are libraries that already do this for you, for example serve-index.
Doing it yourself
This is a modified version of your code to show file content or list the files/directories in a directory. I've added some comments to explain what's happening, but feel free to ask more questions if something is not clear.
const express = require("express");
const path = require("path");
const fs = require("fs");
const app = express();
const listingPath = path.join(__dirname, "shaders");
app.get("*", (req, res) => {
// Build the path of the file using the URL pathname of the request.
const filePath = path.join(listingPath, req.path);
// If the path does not exist, return a 404.
if (!fs.existsSync(filePath)) {
return res.status(404).end();
}
// Check if the existing item is a directory or a file.
if (fs.statSync(filePath).isDirectory()) {
const filesInDir = fs.readdirSync(filePath);
// If the item is a directory: show all the items inside that directory.
return res.send(filesInDir);
} else {
const fileContent = fs.readFileSync(filePath, 'utf8');
// If the item is a file: show the content of that file.
return res.send(fileContent);
}
});
const PORT = 3000;
app.listen(PORT, () => {
console.log("listening on port ", PORT);
});
You can use this as a base to make a template that includes links to the files/directories, to include a link to the parent directory, to show more meta data ...