When The Webpack Dev Server Does Not Close It’s Port

I use Visual Studio Code for my Angular Development. It is lightweight, free and has a portable version which I carry around with me everywhere just in case. However, I have recently been experiencing more frequent occurrences where pressing Ctrl-C (^C) to stop the Webpack Dev Server integrated with the Angular CLI does not actually terminate that listening socket connection. To work around this, I created a little PowerShell script that I can just run to cleanup any orphaned connections that Webpack Dev Server may have left open in error. I am providing this with an absolute “AS IS” disclaimer. Use it if you like, but know what you are doing first!

You would be typically greeted by the friendly message below first when doing an “ng serve”

I am running the default port 4200, and I already know that I am not running any other application using Webpack Dev Server at that time. So, I go ahead and run the PowerShell script code below. The parameters below are the ones I found pertaining to my use case.

 $netstat = netstat -ano | findstr :4200 | findstr ESTABLISHED 
 $PortNumRegex = [regex]"(\d+)$";
 $portList = new-object system.collections.arraylist

 foreach($stat in $netstat)
 {
    $PortNum = $PortNumRegex.Match($stat).Captures[0].Value;    
    if(!$portList.Contains($PortNum))
    {
        $portList.Add($PortNum);
    }
  }

  foreach($port in $portList)
  {
    Write("Killing Process " +$port);
    &tskill $port
  }