matthew56k
matthew56k

Reputation: 23

how to serve a directory with express?

I would like to create a simple express server that sends a directory like the image following: Browser directory picture

const express = require('express');
const path = require('path');
const app = express();

app.use(express.static(path.join(__dirname, 'shaders')));

app.use('*', (req, res) => {
  res.sendFile((path.join(__dirname, 'shaders')));
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log('listening on port ', PORT);
});

This code displays Cannot GET / in the browser window.

Upvotes: 2

Views: 4580

Answers (3)

BenjaVR
BenjaVR

Reputation: 550

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

Upvotes: 1

aw04
aw04

Reputation: 11177

This code displays Cannot GET / in the browser window.

Sending a GET to / will fallback to your app.use * as you don't have a route defined. It's not clear what this should do as you're returning a directory instead of a file, which isn't going to work.

If you'd like to access a specific file, you need to request it directly as localhost:3000/shaders/xxx, etc. The use of express.static appears to be correct.

Upvotes: 0

Ankit Kumar Rajpoot
Ankit Kumar Rajpoot

Reputation: 5600

You can use a static folder for sharing or fetch files via GET request.

app.use(express.static(path.join(__dirname, 'shaders')));

Upvotes: 2

Related Questions