title: Why is my powershell localhost server so slow?
body: <p>I bodged together a simple local server for hosting a HTML-only web app. I need it because some features, like AJAX requests, do not work from HTML directly open from filesystem.</p>
  <p>It looks like this and actually works.</p>
  <pre><code># source: https://gist.github.com/19WAS85/5424431
  
  $http = [System.Net.HttpListener]::new()
  # Hostname and port to listen on
  $http.Prefixes.Add(&quot;http://localhost:8080/&quot;)
  # Start the Http Server
  $http.Start()
  
  Add-Type -AssemblyName System.Web
  # Log ready message to terminal
  if ($http.IsListening) {
      write-host &quot;HTTP Server Ready!  &quot; -f 'black' -b 'gre'
      write-host &quot;$($http.Prefixes)&quot; -f 'y'
      #write-host &quot;then try going to $($http.Prefixes)other/path&quot; -f 'y'
  }
  
  #New-PSDrive -Name MyPowerShellSite -PSProvider FileSystem -Root $PWD.Path
  # INFINTE LOOP
  # Used to listen for requests
  while ($http.IsListening) {
      # Get Request Url
      # When a request is made in a web browser the GetContext() method will return a request object
      # Our route examples below will use the request object properties to decide how to respond
      $context = $http.GetContext()
  
      if ($context.Request.HttpMethod -eq 'GET') {
  
          # We can log the request to the terminal
          write-host &quot;$($context.Request.UserHostAddress)  =&gt;  $($context.Request.Url)&quot; -f 'mag'
  
  
          $URL = $context.Request.Url.LocalPath
  
          # Redirect root to index.html
          if($URL -eq &quot;/&quot;) {
            $URL = &quot;/index.html&quot;
          }
          $Content = Get-Content -Encoding Byte -Path &quot;web/$URL&quot;
          $Context.Response.ContentType = [System.Web.MimeMapping]::GetMimeMapping(&quot;web/$URL&quot;)
          $Context.Response.OutputStream.Write($Content, 0, $Content.Length)
          $Context.Response.Close()
  
      }
      # powershell will continue looping and listen for new requests...
  
  }
  </code></pre>
  <p>However the requests take an insane amount of time. There's something wrong with how the files are read and written to the output stream.</p>
  <p>Is there a fix? It's so slow that it's basically useless. To try it, make sure you run it somewhere where a <code>web/</code> sub folder exists. The low speed can be easily tested by trying to open a photo for example.</p>