ZiiMakc
ZiiMakc

Reputation: 37056

Run npm script on termination from console "CTRL+C"

I want to run yarn dev to start pm2 and webpack in watch mode for development. Problem is that I need to kill pm2 instance (run yarn pm2:del) when I terminate manually pressing "CTRL+C". How can it be done?

package.json:

  "scripts": {
    "dev": "yarn pm2:del && yarn pm2:dev && yarn wp:dev",
    "pm2:dev": "pm2 start ecosystem.config.js --only dev",
    "pm2:del": "pm2 delete all || exit 0",
    "wp:dev": "webpack --mode=development --watch"
  }

Upvotes: 0

Views: 1027

Answers (2)

ZiiMakc
ZiiMakc

Reputation: 37056

I've created dev.sh script:

#!/bin/bash
yarn pm2:del
yarn pm2:dev
yarn wp:dev
yarn pm2:del

And run it using yarn dev:

 "scripts": {
    "dev": "sh ./scripts/dev.sh",
    "pm2:dev": "pm2 start ecosystem.config.js --only dev",
    "pm2:del": "pm2 delete all || exit 0",
    "wp:dev": "webpack --mode=development --watch"
  }

Upvotes: 0

ridvanaltun
ridvanaltun

Reputation: 3020

I made some research and found this: how to close server on ctrl+c when in no-daemon

pm2 kill && pm2 start ecosystem.json --only dev --no-daemon

It works if you run pm2 alone but you are running 2 programs together, so give it a try below script:

{
    "scripts": {
        "dev": "yarn pm2:del && yarn pm2:dev && yarn wp:dev && yarn pm2:del"
    }
}

How does it work?

  • first, kill all pm2 daemons
  • start a pm2 daemon
  • start webpack
  • finally, kill all pm2 daemons again, it will run when you press CTRL + C

Upvotes: 1

Related Questions