I'm wondering if it's possible to run a program in WSL from an Electron application on Windows.
The situation is that I have a binary which only runs on *nix systems that I want to execute in the background of my desktop Electron app. The binary itself can be included as part of the Electron package, so I know it will be available.
I'm aware WSL isn't always installed on Windows systems, but in cases where it is, would it be possible to somehow "call into it" to run the binary?
I tried researching the question, but have only been able to find information about running Electron itself from inside WSL which is not what I'm looking for.
CodePudding user response:
I'm honestly not familiar with Electron, but it shouldn't be a problem at all. WSL itself can be launched as a standard Windows .exe
, which can then specify the Linux application to run on the command-line. The results are returned to stdout
.
For instance:
const { execFile} = require('child_process');
execFile('wsl.exe', ['--exec','ls','-la'], {}, (err, stdout, stderr) => {
console.log(err);
console.log(stdout);
console.log(stderr)
});
The
--exec
specifies the binary to run. This isn't strictly necessary, but it avoids the overhead of running a standard shell (e.g. Bash) and then having Bash execute the binary.The
ls
is, of course, the binary. As to the path of your binary that is packaged in the Electron, that's where I'd stumble a bit. That will be a Windows path (although exactly where it is bundled in the Electron app, I don't know. Regardless, you'll need to convert it to the equivalent WSL/Linux path using thewslpath
command.For instance, similar to the above (and without any real error handling):
const { execFile} = require('child_process'); execFile('wsl.exe', ['--exec','wslpath','C:\\Windows\\notepad.exe'], {}, (err, stdout, stderr) => { console.log(err); console.log(stdout); console.log(stderr) });
stdout
will contain/mnt/c/Windows/notepad.exe
.
Note that, if your Linux application requires and environment variables to be pre-configured, that will need to be done through the WSLENV
variable.