问题
I am trying to make a button open an exe file in computer but it doesn't open and it gives me this error
Uncaught ReferenceError: require is not defined at runExe (main.js:61) at HTMLButtonElement.onclick
here is the code for my button
<button onclick="runExe()" id="button">click</button>
and i got this code form the internet and when i remove the function runExe() the exe file opens when i start the app and i want it to only open when button is clicked.
here is the code to open the exe file
function runExe(){
var child = require('child_process').execFile;
var executablePath = "winRAR.exe";
child(executablePath, function(err, data) {
if(err){
console.error(err);
return;
}
console.log(data.toString());
});}
回答1:
The error message says you cannot use require
.
You are trying to run that code in the renderer process. If the distinction between main and renderer is new, see https://www.electronjs.org/docs/tutorial/application-architecture#main-and-renderer-processes
One way to do what you want is to instead have the rendered process send the open request to the main process, where the require will work, and where opening a child process should work.
BTW, I don't know if shell.openItem()
(https://www.electronjs.org/docs/api/shell) can be used to start any exe? If so, that might be the better way to do it.
来源:https://stackoverflow.com/questions/59889508/how-can-i-open-an-exe-file-using-a-button-inelectron