// const express = require('express'); // const serveIndex = require('serve-index'); // const bodyParser = require('body-parser'); // const path = require('path'); // const cors = require('cors'); // const app = express(); // const port = 3000; // // Enable CORS for all routes // app.use(cors()); // app.use(bodyParser.json()); // // Initial directory path // let currentDirectory = path.join(__dirname, 'public'); // // Set root path for directory listing // app.use('/', express.static(currentDirectory), serveIndex(currentDirectory, { icons: true })); // // Start the server // app.listen(port, () => { // console.log(`Server is running on http://localhost:${port}`); // }); const express = require("express"); const path = require("path"); const fs = require("fs"); const app = express(); const listingPath = path.join(__dirname, "public"); app.get("*", (req, res) => { const decodedPath = decodeURIComponent(req.path); const filePath = path.join(listingPath, decodedPath); if (!fs.existsSync(filePath)) { return res.status(404).end(); } if (fs.statSync(filePath).isDirectory()) { const filesInDir = fs.readdirSync(filePath); const links = filesInDir.map(file => { const encodedFile = encodeURIComponent(file); const fileLink = path.join(req.path, encodedFile); let linkAttributes = ""; let fileLocationEncoding = "" console.log(fileLink) let convertedString = fileLink.replace(/\\/g, '/'); console.log(convertedString) // Check if the file is of a specific type that should open in a new window/tab const fileExtension = path.extname(file).toLowerCase(); if (isFileTypeToOpenInNewTab(fileExtension)) { fileLocationEncoding = 'http://localhost:3000/' + convertedString linkAttributes = `onclick="window.open('${fileLocationEncoding}', 'fileWindow', 'width=600,height=400');"`; return `
  • ${file}
  • `; } else { return `
  • ${file}
  • `; } }); return res.send(``); } else { const fileExtension = path.extname(filePath).toLowerCase(); if (fileExtension === ".pdf") { // For PDF files, send the file to be displayed in the browser. const fileStream = fs.createReadStream(filePath); fileStream.pipe(res); } else { // For other file types, set content type and send file. const contentType = getContentType(fileExtension); res.set("Content-Type", contentType); return res.sendFile(filePath); } } }); // Function to get content type based on file extension function getContentType(fileExtension) { switch (fileExtension) { case ".txt": return "text/plain"; case ".png": return "image/png"; // Add more content types as needed default: return "application/octet-stream"; } } // Function to check if the file type should open in a new window/tab function isFileTypeToOpenInNewTab(fileExtension) { const supportedFileTypes = [".pdf", ".png", ".txt"]; // Add more file types as needed return supportedFileTypes.includes(fileExtension); } const PORT = 3000; app.listen(PORT, () => { console.log("Server is running on http://localhost:" + PORT); });