Can't stop my startup script on debian squeeze

I'm trying to set up a deployment for a webapp I'm doing and I'm having some problems with start script. Here's what I done so far:

#!/bin/bash
DIR=/webroot/webapp.com
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
NODE_PATH=/usr/local/lib/node_modules
NODE=/usr/local/bin/node

test -x $NODE || exit 0

function start_app {
  NODE_ENV=production nohup "$NODE" "$DIR/production/WebApp/server.js"
  echo $! > "$DIR/production/WebApp/webapp.pid"
}

function stop_app {
  kill `cat $DIR/production/WebApp/webapp.pid`
}

case $1 in
   start)
      start_app ;;
    stop)
      stop_app ;;
    restart)
      stop_app
      start_app
      ;;
    *)
      echo "usage: webapp.com {start|stop}" ;;
esac
exit 0

I can start it like that but when I try to stop it I get this:

ssh mydomain.com /etc/init.d/webapp.com restart
cat: /webroot/webapp.com/production/WebApp/webapp.pid: No such file or directory
kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]

The error is fairly straight forward:

cat: /webroot/webapp.com/production/WebApp/webapp.pid: No such file or directory

Does this file exist?

If not, the question is why. My hunch is that this command is failing:

echo $! > "$DIR/production/WebApp/webapp.pid"

But since you never verify that it actually created the file, you don't catch the error.

Does the directory /webroot/webapp.com/production/WebApp/ exist? Does your user have read/write/execute permission on that directory?

Another possibility, since this directory is being placed in /webroot/webapp.com/production/WebApp is that it's getting deleted by the application. You may have to store the pid file elsewhere. Have you tried that?

The problem here is that your webapp.pid file isn't actually being created until after your node app exits, and it won't exit until your startup script kills it, which it can't do without the .pid file.

You need to run node in the background so the code that creates the .pid file actually gets a chance to run:

NODE_ENV=production nohup "$NODE" "$DIR/production/WebApp/server.js" &