Search code examples
javascriptnode.jsnodemon

Stop nodemon programmatically after run


I'm working on an API that runs in the background, we have some helper methods that need to be launch as such nodemon --exec babel-node commands/router.js to display all routes for instance.

Note that node commands/router.js cannot work as we need babel

At the moment, the method runs without problem but I need to stop nodemon from running after execution. I understand that nodemon is supposed to keep running after execution but our project is designed as such and I need to use nodemon for execution and then kill it.

How can I kill/stop nodemon after run?

Code

package.json

{
  ...
  scripts: {
    "start": "nodemon --exec babel-node index.js",
    "router": "nodemon --exec babel-node commands/router.js"
  },
  ...
}

router.js

const script = () => {
  // Fetch and display routes
}

script()

Solution

  • EDIT:

    From Nodemon documentation, the correct way to handle this use case is to manually kill the process with the gracefulShutdown method, like so:

    process.once('SIGUSR2', function () {
      gracefulShutdown(function () {
        process.kill(process.pid, 'SIGUSR2');
      });
    });
    

    You can read more here.