title: How to rebuild node.js addon when source changes
body: <p>I have a node.js app and I have created a native addon.  (In case you need background info, native addons for node.js can be created <a href="https://nodejs.org/api/addons.html" rel="noreferrer">like this</a>).</p>
  
  <p>In my development environment I want it to watch source files (these are C++ source files, in this case) and automatically rebuild my addon when the C++ source files change, and also automatically restart the node application after the build completes.</p>
  
  <p>I'm certain there's more than one way to accomplish this, but I went down the road of trying nodemon.  But I couldn't figure out how to get nodemon to wait for the build to finish before restarting the application.</p>
  
  <p>I figure npm can probably do this itself too with a script, perhaps with some kind of a watch package.  So I'm open to alternative approaches if there's something easier.</p>
  
  <p>So when any of my source files change, really all I need is for <code>node-gyp build</code> to run at the right point in the restart workflow (stop node, recompile, restart node). Right now it rebuilds the addon and restarts the application <strong>without waiting for the build to complete</strong>, and that's undesirable.</p>
  
  <p>Here's my nodemon.json file:</p>
  
  <pre><code>{
    "watch": [
      "addon/"
    ],
    "ignore": [
      "addon/build/"
    ],
    "events": {
      "restart": "cd addon &amp;&amp; node-gyp build"
    },
    "ext": "js,json,cc,h"
  }
  </code></pre>
  
  <p>This doesn't work because the "restart" is like an event, in that my script that runs node-gyp fires and executes, but it doesn't block restarting until the build is finished.</p>
  
  <p>I was hoping it would work more like middleware, where it would run the build script after the app is terminated, but before it restarts the app.  I also consulted <a href="https://github.com/remy/nodemon/issues/310" rel="noreferrer">this relevant nodemon issue</a>, but there's no concrete suggestion there about how to make that happen.</p>
  
  <p>I need to change something so that the rebuild (node-gyp step) will happen automatically when the source changes and then restart nicely.</p>
  
  <p><em>Note: Later I'll restructure it so that it only rebuilds the addon when the relevant C++ source files change, and just restarts the app when .js files change without rebuilding the C++ addon, but first I need to figure out getting the node-gyp build step to happen at the right time.</em></p>