title: How do I restart a Node.js server internally in the script on global error?
body: <p>I've been browsing around but to no success. I've found some npm packages like nodemon and forever but documentation doesn't explain how to call a restart inside the script properly.</p>
  
  <p>I've found <a href="https://stackoverflow.com/questions/24666696/restart-a-node-js-app-from-code-level">this</a> code snippet on another question but I'm not using Express or other frameworks since the script is using a pulling service not a response one.</p>
  
  <p>This is code I've made so far using internal Node.js dependencies but no luck.</p>
  
  <hr>
  
  <pre><code>'use strict'
  
  process.on('uncaughtException', (error) =&gt; {
    console.error('Global uncaughtException error caught')
    console.error(error.message)
    console.log('Killing server with restart...')
    process.exit(0)
  })
  
  process.on('exit', () =&gt; {
    console.log('on exit detected')
    const exec = require('child_process').exec
    var command = 'node app.js'
    exec(command, (error, stdout, stderr) =&gt; {
      console.log(`error:  ${error.message}`)
      console.log(`stdout: ${stdout}`)
      console.log(`stderr: ${stderr}`)
    })
  })
  
  setTimeout(() =&gt; {
    errorTriggerTimeBomb() // Dummy error for testing triggering uncaughtException
  }, 3000)
  </code></pre>
  
  <hr>
  
  <p>Just to note I'm running the server on Termux, a Linux terminal app for android. I know it's better to run from desktop but I'm always at a WiFi or mobile data area and that I don't like leaving my PC on overnight.</p>