Reputation: 6015
I have to execute a node command within another node process as shown below:
require('child_process').exec (`${<path of current node executable>} someModule`);
How can i retrieve the node executable path on runtime to execute this command.
Upvotes: 17
Views: 13008
Reputation: 853
process.execPath
should be what you require.
process.argv0
is not alway pointed to node
binary.
As the in the official Node document.
The process.argv0 property stores a read-only copy of the original value of argv[0] passed when Node.js starts.
In the example of the official document, it demo the case that process.argv0
is not the node binary. customArgv0
is for exec
's -a
flag.
$ bash -c 'exec -a customArgv0 ./node'
> process.argv[0]
'/Volumes/code/external/node/out/Release/node'
> process.argv0
'customArgv0'
If you are trying to execute another node app, how about taking a look at child_process.fork
?
You code then should be as follows.
// fork()'s first argument should be the same as require();
// except that fork() executes the module in a child process
require('child_process').fork(`someModule`);
As stated in document, fork()
use the same node binary as process.execPath
, or you can specify other node binary to execute the module.
By default, child_process.fork() will spawn new Node.js instances using the process.execPath of the parent process. The execPath property in the options object allows for an alternative execution path to be used.
Upvotes: 28