Skip to content

IVirtualServer

David Ortner edited this page Jan 20, 2025 · 12 revisions

IVirtualServer represents a simulated HTTP server that serves files from a directory on the local file system.

When a specified base URL or path matches the request URL, the virtual server will respond with the file content from the local file system.

This can be useful for server-side rendering or testing purposes.

Signature

interface IVirtualServer

Properties

Property Type Default Description
url string | RegExp A string or RegExp to match against the request URL. The current window origin will be used if the URL doesn't contain an origin (e.g. "/path/to/virtual-server/").
directory string File system directory. The provided directory is resolved relative to the current working directory.

Example 1

File structure:
 - {root}
   - build
     - index.html
     - style.css
     - script.js
import { Window } from "happy-dom";

const window = new Window({
   settings: {
      fetch: : {
         virtualServers: [
            {
               url: 'https://localhost:8080',
               directory: "./build"
            }
         ]
      }
   }
});

const childWindow = window.open('https://localhost:8080');

// Outputs "script.js"
console.log(childWindow.document.querySelector('script').getAttribute('src'));

Example 2

File structure:
 - {root}
   - build
     - index.html
     - style.css
     - script.js
import { Browser, IVirtualServer } from "happy-dom";

const browser = new Browser({
   settings: {
      fetch: : {
         virtualServers: [
            {
               url: /https:\/\/localhost:8080\/[a-z]{2}\/[a-z]{2}\//,
               directory: "./build"
            }
         ]
      }
   }
});

const page = browser.newPage();

await page.goto("https://localhost:8080/gb/en/");

// Outputs "script.js"
console.log(page.mainFrame.document.querySelector('script').getAttribute('src'));
Clone this wiki locally