UNPKG

five-server

Version:

Development Server with Live Reload Capability. (Maintained Fork of Live Server)

48 lines 2.15 kB
"use strict"; /** * @author Yannick Deubel (https://github.com/yandeu) * @copyright Copyright (c) 2021 Yannick Deubel * @license {@link https://github.com/yandeu/five-server/blob/main/LICENSE LICENSE} */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.findIndex = void 0; const path_1 = require("path"); const fs_1 = require("fs"); const helpers_1 = require("../helpers"); const node_url_1 = __importDefault(require("node:url")); /** Checks if there is an index file and modifies req.url */ const findIndex = (root, withExtension = 'unset', extensions = ['html', 'php']) => { return async (req, res, next) => { const reg = new RegExp(`(${extensions.join('|')})$`); const pathname = node_url_1.default.parse(req.url).pathname || ''; const isAllowedExtension = reg.test(pathname); const hasExtension = (0, path_1.extname)(pathname) !== ''; if (withExtension === 'always' && !hasExtension) return next(); else if (withExtension === 'avoid' && isAllowedExtension) return next(); else if (withExtension === 'redirect') { if (isAllowedExtension) { const redirectTo = req.url.replace((0, path_1.extname)(pathname), ''); return res.redirect(redirectTo); } } if (!hasExtension) { // get the absolute path const absolute = (0, path_1.resolve)((0, path_1.join)(root + pathname)); // check if file exists and modify req.url extensions.forEach(ext => { if ((0, fs_1.existsSync)(`${absolute}.${ext}`)) req.url = (0, helpers_1.removeDoubleSlash)(`${pathname}.${ext}`); else if ((0, fs_1.existsSync)(`${absolute}/index.${ext}`)) req.url = (0, helpers_1.removeDoubleSlash)(`${pathname}/index.${ext}`); }); } next(); }; }; exports.findIndex = findIndex; //# sourceMappingURL=findIndex.js.map