To execute an application using Electron, we are going to use the child_process
class of Node.js. From child_process
we'll use execFile
, this function is similar to child_process.exec()
except it does not execute a subshell but rather the specified file directly. This makes it slightly leaner than child_process.exec
.
Executing a program
To open an executable, we'll need only the path where the executable is located. The following code should execute Mozilla Firefox Browser (note that in your system the path should vary).
Note that the filepath uses double slash (\\
) as the slash is inverted we use double slash to escape a single slash (\
) used in Windows platforms.
var child = require('child_process').execFile;
var executablePath = "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe";
child(executablePath, function(err, data) {
if(err){
console.error(err);
return;
}
console.log(data.toString());
});
Executing a program with parameters
If the execution of a program requires parameters, with node.js execFile you're allowed to send parameters easily. Declare an array of strings, every item is a parameter.
The following example will start Google Chrome in incognito mode thanks to the --incognito
flag (parameter) which can be used with our code :
var child = require('child_process').execFile;
var executablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
var parameters = ["--incognito"];
child(executablePath, parameters, function(err, data) {
console.log(err)
console.log(data.toString());
});
Notes
- Unless the executable files are in the same location of your project, you'll need to provide the full path always.
Read more about child_process in the official Node.js documentation here. Have fun