Search code examples
javascriptnode.jsexecsystem-calls

A way to call execl, execle, execlp, execv, execvP or execvp from Node.js


POSIX systems expose family of exec functions, that allow one to load something maybe different into current process, keeping open file descriptors, process identifier and so on.

This can be done for variety of reasons, and in my case this is bootstrapping — I want to change command line options of my own process, and then reload it over existing process, so there would be no child process.

Unfortunately, to much of my surprise, I could not find the way to call any of exec* functions in Node.js. So, what is the correct way to replace currently running Node.js process with other image?


Solution

  • I have created a module to invoke execvp function from NodeJS: https://github.com/OrKoN/native-exec

    It works like this:

    var exec = require('native-exec');
    
    exec('ls', {
      newEnvKey: newEnvValue,
    }, '-lsa'); // => the process is replaced with ls, which runs and exits
    

    Since it's a native node addon it requires a C++ compiler installed. Works fine in Docker, on Mac OS and Linux. Probably, does not work on Windows. Tested with node 6, 7 and 8.