, , ,

Recently i came up with situation where i was working with node server file, and i had to restart the node server for every change manually, and i felt that as a discomfort.

Even though there are tools out there like node-supervisor, forver, etc to do the job, I want to do it just with fswatch, because i wanted similar thing when i work in different frameworks or code and language, say for instance trying out something in scala, and i need to run the file everytime. So it will come in handy.

So i started trying out things, and finally came up with a shell script that can be passed to the fswatch with the following command.

	fswatch -o folder_to_watch | xargs -n1 './shell_script.sh'

The shell script is listing the running process with ps, and search for my process with grep.
awk gets the pid and kills the process and finally restart the process.

start_node_cmd="nohup node $server_file >> node.out &"
echo $start_node_cmd

echo 'There is a change in file, restarting node'
ps | grep "[n]ode $server_file$" | awk '
	if($1!="") {
		print "killing process: "$1;
		system("kill " $1)

echo "starting server"
eval "$start_node_cmd"

nohup command & is used to start the process in background and redirecting output to node.out also ignoring SIGHUP signal, nohup by default it redirects output to nohup.out.

The reason i had to use grep ‘[n]ode’ is to exclude the grep process from the process list.