node express | directory to html | html music player | Search

This Node.js module exports two functions: handleDirectory and BASE_DIRECTORY. The handleDirectory function handles requests to directories, resolving file paths, checking permissions and types, and generating HTML responses based on the file type and request authentication.

Run example

npm run import -- "node express directory handler"

node express directory handler

const path = require('path')
const fs = require('fs')
const BASE_DIRECTORY = process.env.BASE_DIRECTORY || process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE
const directoryToHtml = importer.import("directory to html")

async function handleDirectory(req, res, next) {
  let basePath = path.resolve(BASE_DIRECTORY)

  let combined = path.join(basePath, decodeURIComponent(req.path))
  console.log(combined, req.authenticated)

  if(!fs.existsSync(combined)) {
    return next()
  }

  if(path.extname(combined).toLocaleLowerCase() == '.mp3') {

    if(req.url.includes('?raw=true')) {
      return res.sendFile(combined)
    }

    return res.send(importer.interpret('html music player').code
      .replaceAll('{FILE_URL}', req.path)
      .replaceAll('{SESSION}', req.authenticated ? req.authenticated : ''))
  }

  if((req.authenticated || combined.includes('stable-diffusion-webui/outputs')) 
    && (path.extname(combined).toLocaleLowerCase() == '.png' 
    || path.extname(combined).toLocaleLowerCase() == '.jpg' 
    || path.extname(combined).toLocaleLowerCase() == '.jpeg')
  ) {

    if(req.url.includes('?raw=true')) {
      return res.sendFile(combined)
    }

    return res.send(importer.interpret('html image viewer').code
      .replaceAll('{FILE_URL}', req.path)
      .replaceAll('{SESSION}', req.authenticated ? req.authenticated : ''))
  }

  if(req.authenticated && fs.statSync(combined).isFile()) {
    return res.sendFile(combined)
  }

  if(!fs.statSync(combined).isDirectory()) {
    return res.status(403).send('Forbidden')
  }

  let html = await directoryToHtml(combined, req.path.split('/').length > 2, req.authenticated)

  return res.send(html)
}

module.exports = {
  handleDirectory,
  BASE_DIRECTORY
}

What the code could have been:

// Import required modules
const path = require('path');
const fs = require('fs');
const { importFunction } = require('./importFunction'); // Assuming the importer module is defined in a separate file

// Define constants
const DIRECTORY_TO_HTML_IMPORT = importFunction('directory to html');
const DIRECTORY_TO_HTML = DIRECTORY_TO_HTML_IMPORT.code;

// Define the BASE_DIRECTORY environment variable
const BASE_DIRECTORY = process.env.BASE_DIRECTORY || process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;

// Define a helper function to get the file extension
function getFileExtension(filePath) {
  return path.extname(filePath).toLocaleLowerCase();
}

// Define a helper function to check if a file is an image
function isImage(filePath) {
  return ['.png', '.jpg', '.jpeg'].includes(getFileExtension(filePath));
}

// Defining the handleDirectory function
async function handleDirectory(req, res, next) {
  try {
    // Get the base path
    const basePath = path.resolve(BASE_DIRECTORY);

    // Get the combined path
    const combined = path.join(basePath, decodeURIComponent(req.path));

    // Log the path and authentication status
    console.log(combined, req.authenticated);

    // Check if the path exists
    if (!fs.existsSync(combined)) {
      // If the path does not exist, call the next middleware
      return next();
    }

    // Check if the file is an MP3
    if (getFileExtension(combined) === '.mp3') {
      // If the?raw=true query parameter is present, send the file directly
      if (req.url.includes('?raw=true')) {
        return res.sendFile(combined);
      }

      // Otherwise, send the HTML music player code
      return res.send(DIRECTORY_TO_HTML
       .replaceAll('{FILE_URL}', req.path)
       .replaceAll('{SESSION}', req.authenticated? req.authenticated : ''));
    }

    // Check if the file is an image
    if ((req.authenticated || combined.includes('stable-diffusion-webui/outputs'))
      && isImage(combined)) {
      // If the?raw=true query parameter is present, send the file directly
      if (req.url.includes('?raw=true')) {
        return res.sendFile(combined);
      }

      // Otherwise, send the HTML image viewer code
      return res.send(DIRECTORY_TO_HTML
       .replaceAll('{FILE_URL}', req.path)
       .replaceAll('{SESSION}', req.authenticated? req.authenticated : ''));
    }

    // Check if the file is a valid file and the user is authenticated
    if (req.authenticated && fs.statSync(combined).isFile()) {
      // Send the file directly
      return res.sendFile(combined);
    }

    // Check if the path is a directory
    if (!fs.statSync(combined).isDirectory()) {
      // If the path is not a directory, send a 403 error
      return res.status(403).send('Forbidden');
    }

    // Get the HTML for the directory
    const html = await DIRECTORY_TO_HTML_IMPORT(combined, req.path.split('/').length > 2, req.authenticated);

    // Send the HTML
    return res.send(html);
  } catch (error) {
    // Log any errors that occur
    console.error(error);

    // Send a 500 error
    return res.status(500).send('Internal Server Error');
  }
}

// Export the handleDirectory function and BASE_DIRECTORY
module.exports = {
  handleDirectory,
  BASE_DIRECTORY
};

Overview

This is a Node.js module that exports two functions: handleDirectory and BASE_DIRECTORY.

Functions

handleDirectory

An asynchronous function that handles requests to directories. It takes three parameters:

Logic

  1. Resolves the base path of the directory using environment variables.
  2. Combines the base path with the request path to get the full path.
  3. Checks if the file exists. If not, it calls the next middleware.
  4. Checks the file extension and type (e.g., audio file, image file). Depending on the type, it:
  5. If the file is a PNG, JPG, or JPEG image and the request is authenticated, returns an HTML page with an image viewer.
  6. If the request is authenticated and the file is a single file, returns the file.
  7. If the file is not a directory, returns a 403 Forbidden error.
  8. Otherwise, uses the directoryToHtml function to generate an HTML list of files in the directory and returns it.

BASE_DIRECTORY

An environment variable that represents the base directory of the application. If not set, it defaults to the HOME directory.