UNPKG

five-server

Version:

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

42 lines 1.77 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} */ Object.defineProperty(exports, "__esModule", { value: true }); exports.findIndex = void 0; const path_1 = require("path"); const fs_1 = require("fs"); /** 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 isAllowedExtension = reg.test(req.url); const hasNoExtension = (0, path_1.extname)(req.url) === ''; if (withExtension === 'always' && hasNoExtension) return next(); if (withExtension === 'avoid' && isAllowedExtension) return next(); if (withExtension === 'redirect') { if (isAllowedExtension) { const reg = new RegExp(`${(0, path_1.extname)(req.url)}$`); return res.redirect(req.url.replace(reg, '')); } } if (hasNoExtension) { // get the absolute path const absolute = (0, path_1.resolve)((0, path_1.join)(root + req.url)); // check if file exists and modify req.url extensions.forEach(ext => { if ((0, fs_1.existsSync)(`${absolute}.${ext}`)) req.url = req.url += `.${ext}`; else if ((0, fs_1.existsSync)(`${absolute}/index.${ext}`)) req.url = req.url += `/index.${ext}`; }); } next(); }; }; exports.findIndex = findIndex; //# sourceMappingURL=findIndex.js.map