Search code examples
javascriptnode.jsprocessspawn

Node spawn process check for timout


I've spawned process which sometimes take to long to run, my question is there is a way to limit this process time ? for example kill this process after 3 min ?


Solution

  • You can use process.kill in a timeout. But remember to cancel the timeout if the child finishes before it gets fired.

    Take a look at this example:

    This is child.sh that returns after 3 seconds:

    #!/bin/bash
    sleep 3
    echo DATA FROM CHILD
    

    This is a Node program that spawns that child:

    var seconds = process.argv[2] || 2;
    var spawn = require('child_process').spawn;
    var child = spawn('bash', ['child.sh'], {detached: true});
    var stopped;
    var timeout = setTimeout(() => {
      console.log('Timeout');
      try {
        process.kill(-child.pid, 'SIGKILL');
      } catch (e) {
        console.log('Cannot kill process');
      }
    }, seconds*1000);
    child.on('error', err => console.log('Error:', err));
    child.on('exit', () => { console.log('Stopped'); clearTimeout(timeout); });
    child.stdout.on('data', data => console.log(data.toString()));
    

    By default it waits for 2 seconds, which is shorter than the child needs and the child will get killed, but you can add a different number of seconds as a command line argument:

    node nodeprogram.js 10
    

    to wait for 10 seconds which is enough for the child to finish.