title: Running Node app through Grunt
body: <p>I am trying to run my Node application as a Grunt task. I need to spawn this as a child process, however, to allow me to run the watch task in parallel.</p>
  
  <p>This works:</p>
  
  <pre><code>grunt.registerTask('start', function () {
    grunt.util.spawn(
      { cmd: 'node'
      , args: ['app.js']
      })
  
    grunt.task.run('watch:app')
  })
  </code></pre>
  
  <p>However, when changes are detected by the watch task, this will trigger the start task again. Before I spawn another child process of my Node app, I need to kill the previous one.</p>
  
  <p>I can't figure out how to kill the process, however. Something like this does not work:</p>
  
  <pre><code>var child
  
  grunt.registerTask('start', function () {
    if (child) child.kill()
    child = grunt.util.spawn(
      { cmd: 'node'
      , args: ['app.js']
      })
  
    grunt.task.run('watch:app')
  })
  </code></pre>
  
  <p>It appears that:</p>
  
  <ol>
  <li>Even though I store the spawned process in a variable outside of the function context, it does not persist, so the next time the start task is run, child is <code>undefined</code>.</li>
  <li><code>child</code> has no <code>kill</code> function…</li>
  </ol>