'How to start and stop local server automatically?
I have a site on Angular, that needs to be run on local server. But at the same time, the server needs to be started with a shortcut (that I have implemented already), and stopped, when a browser is closed (so it doesn't take resources). I don't really know how to stop a server automatically. Maybe I need some shell script running in the background and checking the state from time to time, or something like that. Any ideas?
Solution 1:[1]
I would write a batch script to check if (e.g Chrome) is running. Check that after every 5 seconds and if found that chrome has been closed then also terminate ng serve serving cmd.
Following script will run cmd1 which lets you ng serve by opening cmd2. cmd1 itself will remain ticking on background checking every 5 sec if chrome.exe is running. If so, it loops again. If no chrome.exe has been found it will terminate window with title ng serve (a.k.a cmd2).
Change set myApp-dir=C:\Users\<username>\IdeaProjects\myApp-frontend to your dir what you want to serve and of course change the <username> to your username. Rest of the code can be left unchanged.
Save to desktop with notepad as something.bat
@ECHO OFF
CLS
:: Directory for the project
set myApp-dir=C:\Users\<username>\IdeaProjects\myApp-frontend
ECHO 1. myApp-frontend ng serve
echo.
:Start
CHOICE /C 1 /M "Choose:"
echo.
:: Note - list ERRORLEVELS in decreasing order
IF ERRORLEVEL 1 GOTO start-app
:start-app
start cmd.exe /k "chdir "%myApp-dir%" & ng serve"
@echo off
:loop
tasklist /FI "ImageName eq chrome.exe" | find /i "chrome" > nul || goto :chrome_exited
:: wait 5 seconds before checking again
timeout /t 5 >nul
echo checking if chrome has exited...
goto :loop
:chrome_exited
echo Chrome has exited! Killing "ng serve" cmd.
set toKill=ng serve
tasklist /V /FI "WINDOWTITLE eq %toKill%" | find /I "%toKill%" >NUL && (taskkill /FI "WINDOWTITLE eq %toKill%" /T /F)
GOTO Start
:End
pause
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
