node.jsnpmbuildtimeoutkill

How to run an npm script with a timeout (kill process if it takes longer then certain amount of time)?


I have an npm build script for Angular:

"build": "ng build my-project-name"

This script often hangs (inside our build pipeline and locally). I'd like to set a timelimit after which the process is killed and restarted. I tried to use a node script with spawn or spawnSync to run npm.cmd run build and explicit use timeout or .kill() being called on returned handle, it looked like the process was killed, but then it's output continued hitting the terminal and terminal had to be killed manually.

Is there any generic way to run an NPM script that will be killed after a given amount of time?


Solution

  • Here is what I ended up using.

    Make a js script timeout.js like this:

    setTimeout(() => process.exit(1), 20000);
    

    Install node package concurrently

    Make NPM script like this:

    {
    "build:with-timeout": "concurrently -k \"node timeout.js\" \"npm run build\""
    }
    

    With -k flag concurrently will send a SIGTERM signal to all other processes when one of them terminates. In my specific case I chose to monitor CPU usage by build process and terminate if its activity falls to near 0 for 2 minutes.