5

My package.json scripts section looks like this.

"scripts": {
  "prestart": "mongod",
  "start": "NODE_ENV=prod node server.js",
  "poststop": "mongo admin --eval 'db.shutdownServer()'",
  "predev": "mongod",
  "dev": "NODE_ENV=dev nodemon server.js"
},

I use pre- and post hooks to start mongod before starting my server. I then kill my server using ctrl+c. Unfortunately, this doesn't execute the poststop script. As a result, calling npm/yarn start/dev for the second time throws an error and aborts because mongod is already running.

Another mongod instance is already running on the /data/db directory, terminating

Can I somehow call poststop on ctrl+c?

tk421
  • 5,775
  • 6
  • 23
  • 34
Janosh
  • 3,392
  • 2
  • 27
  • 35

1 Answers1

4

You need to trap the SIGINT signal and return a success exit code (0) instead

"scripts": {
  "prestart": "mongod",
  "start": "trap 'exit 0' SIGINT; NODE_ENV=prod node server.js",
  "poststop": "mongo admin --eval 'db.shutdownServer()'",
  "predev": "mongod",
  "dev": "NODE_ENV=dev nodemon server.js"
},
Brett Y
  • 7,171
  • 1
  • 28
  • 42