In Electron, passing command line arguments can be achieved using Node.js's process.argv. process.argv is an array containing the command line arguments passed when starting the Node.js process. The first element is the path to the Node.js executable, the second element is the path to the currently executing JavaScript file, and from the third element onwards, it represents user-provided command line arguments.
Example Steps
Suppose we have an Electron application where we want to modify the application's behavior based on command line arguments, such as determining whether to start the application in debug mode based on the input parameters. Below are the specific steps and example code:
-
Accessing Command Line Arguments In Electron's main process (typically
main.jsorindex.js), we can access command line arguments usingprocess.argv.Code Example:
javascriptconst electron = require('electron'); const app = electron.app; app.on('ready', () => { // Access command line arguments const argv = process.argv; console.log(argv); // Output command line arguments for verification let debugMode = false; // Check for specific command line arguments if (argv.includes('--debug')) { debugMode = true; } // Execute different logic based on debug mode if (debugMode) { console.log("Starting the application in debug mode"); // Open developer tools, etc. } else { console.log("Starting the application normally"); } }); -
Passing Parameters When Launching the Electron Application When launching the Electron application from the command line, you can directly add parameters after the command.
Command Line Example:
bashelectron . --debugThis command launches the Electron application and passes the
--debugparameter, allowing your application to decide whether to enable debug mode based on this parameter.
Important Notes
- Make sure to execute the parameter handling logic after the application is ready, typically within the
app.on('ready', callback)callback. - Command line arguments are case-sensitive, so
--debugand--DEBUGare treated as different parameters. - You can use third-party libraries like
yargsorcommanderto more conveniently parse and manage command line arguments.