How to set a maximum execution time of a script with node.js?

Alain Tiemblo picture Alain Tiemblo · Mar 2, 2013 · Viewed 9.8k times · Source

I give my users a flexible way to transform data using JavaScript, executed with Node.js on server-side. With that design, there is 3 issues to consider :

  • Security : I solved the security issue using a sandbox to avoid usage of native Node.js libraries.

  • Resources : we can easily set maximum memory usage using v8 option --max_executable_size. About the CPU usage, I'll see how to manage it using cpulimit or renice, it does not really matter now.

  • Time : I need to limit execution time of my scripts, to avoid them running as hangry zombies. And here I get stuck.

I tried something like :

 node -e '
    setTimeout(function() {
       console.log("timeout");
       process.exit;
    }, 5000);
    console.log("begin");
    while (1);
 '

But this code displays only "begin", it seems that my timeout is never called. Any idea ?

Answer

Glenn Block picture Glenn Block · Jun 9, 2014

You might want to look at tripwire (https://github.com/tjanczuk/tripwire). It is a module that can kill runaway node scripts and you can set a timeout. It is a native node module, so that is one thing to consider, but it works on Mac, Windows and Linux.