node express | zuora eloqua express mock | node express directory handler | Search

The directoryToHtml function takes a directory path and optional parameters, and returns an HTML string representing the directory listing, excluding files starting with a dot or containing explicit content. The function uses fs and path modules to read directory contents and dynamically generate HTML links for files and subdirectories.

Run example

npm run import -- "directory to html"

directory to html

const fs = require('fs');
const path = require('path');

async function directoryToHtml(dirPath, back, session) {
  let files = await fs.readdirSync(dirPath)

  let htmlOutput = `<html>
<head>
<style>
ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  padding: 10px;
  border-bottom: 1px solid #ccc;
}

li:last-child {
  border-bottom: none;
}

i {
  font-size: 18px;
  margin-right: 10px;
  color: #666;
}

span {
  font-size: 16px;
  color: #333;
}

ul {
  padding-left: 20px;
}

ul li {
  padding-left: 10px;
}
</style>
</head>  
<body><h1>Directory Listing</h1><ul>`;

  if(back) {
    htmlOutput += `<li><a href="../?t=${Date.now()}${session ? ('&session=' + session): ''}">Parent directory/</a></li>`;
  }

  files.forEach((file) => {
    const filePath = path.join(dirPath, file);
    const fileStat = fs.statSync(filePath);

    if(file[0] == '.' || file.includes('nsfw') || file.includes('naked') || file.includes('x-rated')) {
      return
    }

    if (fileStat.isDirectory()) {
      htmlOutput += `<li><a href="${encodeURIComponent(file).replaceAll('(', '%28').replaceAll(')', '%29')}/?t=${Date.now()}${session ? ('&session=' + session): ''}">${file}/</a></li>`;
    } else {
      htmlOutput += `<li><a href="${encodeURIComponent(file).replaceAll('(', '%28').replaceAll(')', '%29')}?t=${Date.now()}${session ? ('&session=' + session): ''}">${file}</a></li>`;
    }
  });

  htmlOutput += '</ul></body></html>';

  return htmlOutput
}

module.exports = directoryToHtml

What the code could have been:

const fs = require('fs');
const path = require('path');
const console = require('console');

class DirectoryToHtml {
  /**
   * Returns an HTML directory listing for a given directory path.
   *
   * @param {string} dirPath - The path to the directory to list.
   * @param {boolean} back - Whether to include a link to the parent directory.
   * @param {string} session - The session ID to include in the URL.
   * @returns {string} The HTML directory listing.
   */
  async directoryToHtml(dirPath, back, session) {
    // Check if the directory path exists
    if (!fs.existsSync(dirPath)) {
      throw new Error(`Directory ${dirPath} does not exist.`);
    }

    // Get the list of files in the directory
    const files = await fs.readdir(dirPath);

    // Create the HTML output
    let htmlOutput = `
      <html>
        <head>
          <style>
            /* CSS styles for the directory listing */
          </style>
        </head>
        <body>
          <h1>Directory Listing</h1>
          <ul>
    `;

    // Add a link to the parent directory if requested
    if (back) {
      htmlOutput += `
        <li><a href="../?t=${Date.now()}${session? ('&session=' + session) : ''}">Parent directory/</a></li>
      `;
    }

    // Iterate over the files in the directory
    files.forEach((file) => {
      const filePath = path.join(dirPath, file);
      const fileStat = fs.statSync(filePath);

      // Skip hidden files and files with explicit content
      if (
        file.startsWith('.') ||
        file.includes('nsfw') ||
        file.includes('naked') ||
        file.includes('x-rated')
      ) {
        return;
      }

      // Add a link to the file or directory
      if (fileStat.isDirectory()) {
        htmlOutput += `
          <li>
            <a href="${encodeURIComponent(file).replaceAll('(', '%28').replaceAll(')', '%29')}/?t=${Date.now()}${session? ('&session=' + session) : ''}">${file}/</a>
          </li>
        `;
      } else {
        htmlOutput += `
          <li>
            <a href="${encodeURIComponent(file).replaceAll('(', '%28').replaceAll(')', '%29')}?t=${Date.now()}${session? ('&session=' + session) : ''}">${file}</a>
          </li>
        `;
      }
    });

    // Close the HTML output
    htmlOutput += `
      </ul>
    </body>
    </html>
  `;

    return htmlOutput;
  }
}

module.exports = DirectoryToHtml;

Code Breakdown

Dependencies

Function: directoryToHtml

Parameters

Returns

Functionality

  1. Reads the contents of the directory using fs.readdirSync.
  2. Creates the HTML structure for the directory listing.
  3. Iterates over the directory contents and dynamically generates HTML links for files and subdirectories.
  4. Excludes files starting with a dot (.), containing the words "nsfw", "naked", or "x-rated".
  5. Returns the generated HTML output.

Notes