title: NodeJS child_process and express: terminate previous process and run a new one when a new POST request is made
body: <p>I have this code that calls the <code>nfc-forum-emulate-tag4</code> command on a file that the code also creates, containing a NDEF text record of the data received in the POST request. However, <code>nfc-forum-emulate-tag4</code> runs indefinitely until the tag is scanned or until the process is killed. I want to, every time I get a POST request, kill the previous process and run another one. I have found that with the below code, the <code>execSync</code> blocks the POST request until the emulation process completes, but when I use <code>exec</code> instead of <code>execSync</code>, the command doesn't actually run. (Terrible) code:</p>
  <pre class="lang-js prettyprint-override"><code>const { execSync } = require('child_process')
  const express = require('express')
  const fs = require('fs')
  const app = express()
  function buildNFC(text) {
      const hex = Buffer.from(text)
      const length = text.length+3 
      const initial = Buffer.from([0xd1, 0x01, length, 0x54, 0x02, 0x65, 0x6e])
      return Buffer.concat([initial, hex])
  }
  var child;
  app.post(&quot;/&quot;, function(req, res) {
      const nfcbuffer = buildNFC(req.query.code)
      fs.writeFileSync(&quot;/home/pi/nfc&quot;, nfcbuffer)
      res.send(&quot;Sent &quot; + nfcbuffer.toString('hex'))
      try {
          if(child) {
                  console.log(`pid: ${child.pid}`)
                  execSync(`killall ${child.pid}`, {stdio: 'inherit'})
                  child = null
          }
          else {
                  console.log(`no child running`)
          }
          child = execSync(`cd /home/pi &amp;&amp; nfc-emulate-forum-tag4 ./nfc`, {stdio: 'inherit'})
      } catch {}
  })
  app.listen(3000, () =&gt; console.log(&quot;Listening on port 3000...&quot;))
  </code></pre>
  <p>Thanks in advance!</p>