nodemon events — run tasks at server start, restart, crash, exit

Nikhil John
Netscape
Published in
2 min readOct 7, 2016
The Node Demon!

If you’re developing a NodeJS application, chances are that you use nodemon on your Development Environment.

nodemon wraps your node application and watches for any files that have changed

This is super-useful because you don’t need to restart your server every time you change a file. nodemon works out of the box, with zero configuration. All you need to do is replace node with nodemon in your application start script

{
"name": "...",
"scripts": {
"start-dev": "nodemon app.js",
"start": "node app.js"
}
}

One aspect about npm scripts that doesn’t get enough attention is pre and post script commands. Any arbitrary npm script (let’s name it do-something) can have its own predo-something and postdo-something command, that run before and after your do-something script.

Say you want to run a linter before every app start. You can configure it like so:

{
"name": "...",
"scripts": {
"prestart-dev": "npm run lint",
"start-dev": "nodemon app.js",
"start": "node app.js",
"lint": "grunt jshint"
}
}

Now, every time you run npm run start-dev on your console, you will see:

> npm run lint# 
# npm run lint logs
#
[nodemon] starting `node app.js`

But how do npm pre and post work with nodemon?

Not very well unfortunately. Because nodemon doesn’t run npm start-dev when it restarts the server, the pre command isn’t run either. So this works only the first time the server started.

Luckily, there’s a way around this. nodemon allows for an optional configuration file called nodemon.json in your root folder. And nodemon emits events upon every change in state:

  • start
    child process has started
  • crash
    child process has crashed (nodemon will not emit exit)
  • exit
    child process has cleanly exited (ie. no crash)
  • restart([ array of files triggering the restart ])
    child process has restarted
  • config:update
    nodemon’s config has changed

We can use these to trigger custom tasks.

{
“events”: {
“restart”: “npm run lint”,
“start”: “npm run lint”
}
}

And boom! Every time nodemon restarts your server, your linter runs.

One cool advantage here is that unlike the previous approach, even if your linting fails, nodemon just does a clean exit and waits for you to fix your code, and then restarts your server again. No annoying process exits!

Try this out on your projects and let me know if you have any suggestions to improve this solution.

Happy coding!

--

--

Nikhil John
Netscape

Tips and tricks on Travelling and Web Engineering! Senior Engineer @Microsoft