运行cmd.exe并使用Electron.js进行一些命令

时间:2019-07-16 09:41:18

标签: electron

是否有可能运行cmd.exe并通过electronic.js发出一些命令?

如果是,那我该怎么办?

2 个答案:

答案 0 :(得分:0)

可以通过使用节点child_process来实现,您可以使用以下功能:

    const exec = require('child_process').exec;

function execute(command, callback) {
    exec(command, (error, stdout, stderr) => { 
        callback(stdout); 
    });
};

// call the function
execute('ping -c 4 0.0.0.0', (output) => {
    console.log(output);
});

npm中有许多与此主题相关的软件包。

答案 1 :(得分:0)

在您的main.js文件中,您可以输入以下代码:

//Uses node.js process manager
const electron = require('electron');
const child_process = require('child_process');
const dialog = electron.dialog;

// This function will output the lines from the script 
// and will return the full combined output
// as well as exit code when it's done (using the callback).
function run_script(command, args, callback) {
    var child = child_process.spawn(command, args, {
        encoding: 'utf8',
        shell: true
    });
    // You can also use a variable to save the output for when the script closes later
    child.on('error', (error) => {
        dialog.showMessageBox({
            title: 'Title',
            type: 'warning',
            message: 'Error occured.\r\n' + error
        });
    });

    child.stdout.setEncoding('utf8');
    child.stdout.on('data', (data) => {
        //Here is the output
        data=data.toString();   
        console.log(data);      
    });

    child.stderr.setEncoding('utf8');
    child.stderr.on('data', (data) => {
        // Return some data to the renderer process with the mainprocess-response ID
        mainWindow.webContents.send('mainprocess-response', data);
        //Here is the output from the command
        console.log(data);  
    });

    child.on('close', (code) => {
        //Here you can get the exit code of the script  
        switch (code) {
            case 0:
                dialog.showMessageBox({
                    title: 'Title',
                    type: 'info',
                    message: 'End process.\r\n'
                });
                break;
        }

    });
    if (typeof callback === 'function')
        callback();
}

现在,您可以通过调用以下命令来执行任意命令(示例来自Windows命令提示符,但此功能是通用的)

  run_script("dir", ["/A /B /C"], null);

命令的参数实际上是一个数组["/A /B /C"],最后一个参数是要执行的回调,如果不需要特殊的回调函数,则可以提供null作为参数。