Node Forever!

I really like working with Node on the server side.  That might be because I feel more comfortable in Javascript than Python or PHP or .NET.  I chose Node as the backend for a super simple internal marketing app created a couple months ago.  We only had a couple days to make it work and Node/Express seemed like the quickest way to get it going.  There would only be a couple routes, so that was easy- but it would also require logging in, so MongoDB would be a necessity.  The trickiest part (I think this was outlined in a previous post) was installing the bcrypt library for database password security.

But we figured it out and everything was running smoothly.  Until someone hit the little red ‘X’ in the top right of the command prompt that was running the Node server.  That kicked off some emails marked ‘Urgent’ and made for an early morning for one developer (me).

So I looked into how we could keep the Node server running even if that prompt was closed.  Keep it running forever, even.  And, of course, the answer was Forever- the npm module.

It’s a useful little thing that sets up your server as a daemon (or process- I’m unclear on the terminology).  Either way, it runs in the background, so your window doesn’t need to be open.  It works great, is easy to install, and I could go back to sleep.

But there is one gotcha- particularly for a fumble fingers typist low on sleep.  The command to start a server with Forever is simple: ‘forever start server.js’ (or whatever your server file is called).  But if you forget the ‘start’ part, and just go for ‘forever server.js’, Forever starts the process and appears to fail to assign an id to it.  So it can’t be stopped.  EVER.  That might not be terrible, but it was also preventing me from logging in, meaning it was preventing the boss from logging in, and that was trouble.  Internal marketing numbers were dropping fast! (I have no idea what that means- I just make this stuff work, I don’t know how to sell it).

Of course, nothing is completely unstoppable.  Ctrl-Alt-Delete is your Windows friend!  After trying every command listed by Forever –help, I opened the task manager and found a stray Node.js background process running.  Force quit that and the server stopped.

Moral of the story: type carefully and read the docs.  Powerful modules like Forever are a great help, but can bite you for mistakes.  I also updated my package.json file to make some foolproof scripts to not do this again.  ‘npm start’ now runs ‘net start mongodb && forever start server.js’ to make sure mongo and node are running.  ‘npm stop’ does the opposite.