I'm building an electron app,
I can run shell commands pretty easily with the shell api (https://electronjs.org/docs/api/shell)
This command runs perfect for example:
shell.openItem("D:\test.bat");
This one does not
shell.openItem("D:\test.bat argument1");
How to run electron shell command with arguments?
Locate Command Prompt by entering cmd into the search bar. Click cmd in the search results to open the Command Prompt. Enter the following command, then press Enter to create a file named test-node. Type node followed by the name of the application, which is test-node.
Node. js can run shell commands by using the standard child_process module. If we use the exec() function, our command will run and its output will be available to us in a callback. If we use the spawn() module, its output will be available via event listeners.
The usual way to run a Node. js program is to run the globally available node command (once you install Node. js) and pass the name of the file you want to execute. While running the command, make sure you are in the same directory which contains the app.
shell.openItem
isn't designed for that.
Use the spawn
function of NodeJS from the child_process
core module.
let spawn = require("child_process").spawn;
let bat = spawn("cmd.exe", [
"/c", // Argument for cmd.exe to carry out the specified script
"D:\test.bat", // Path to your file
"argument1", // First argument
"argumentN" // n-th argument
]);
bat.stdout.on("data", (data) => {
// Handle data...
});
bat.stderr.on("data", (err) => {
// Handle error...
});
bat.on("exit", (code) => {
// Handle exit
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With