Path: blob/master/lib/rammerhead/src/util/addStaticDirToProxy.js
6530 views
const mime = require('mime');1const fs = require('fs');2const path = require('path');34// these routes are reserved by hammerhead and rammerhead5const forbiddenRoutes = [6'/rammerhead.js',7'/hammerhead.js',8'/task.js',9'/iframe-task.js',10'/messaging',11'/transport-worker.js',12'/worker-hammerhead.js'13];1415const isDirectory = (dir) => fs.lstatSync(dir).isDirectory();1617/**18*19* @param {import('testcafe-hammerhead').Proxy} proxy20* @param {string} staticDir - all of the files and folders in the specified directory will be served21* publicly. /index.html will automatically link to /22* @param {string} rootPath - all the files that will be served under rootPath23*/24function addStaticFilesToProxy(proxy, staticDir, rootPath = '/', shouldIgnoreFile = (_file, _dir) => false) {25if (!isDirectory(staticDir)) {26throw new TypeError('specified folder path is not a directory');27}2829if (!rootPath.endsWith('/')) rootPath = rootPath + '/';30if (!rootPath.startsWith('/')) rootPath = '/' + rootPath;3132const files = fs.readdirSync(staticDir);3334files.map((file) => {35if (isDirectory(path.join(staticDir, file))) {36addStaticFilesToProxy(proxy, path.join(staticDir, file), rootPath + file + '/', shouldIgnoreFile);37return;38}3940if (shouldIgnoreFile(file, staticDir)) {41return;42}4344const pathToFile = path.join(staticDir, file);45const staticContent = {46content: fs.readFileSync(pathToFile),47contentType: mime.getType(file)48};49const route = rootPath + file;5051if (forbiddenRoutes.includes(route)) {52throw new TypeError(53`route clashes with hammerhead. problematic route: ${route}. problematic static file: ${pathToFile}`54);55}5657proxy.GET(rootPath + file, staticContent);58if (file === 'index.html') {59proxy.GET(rootPath, staticContent);60}61});62}6364module.exports = addStaticFilesToProxy;656667