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

8

是否可以使用Electron.js运行cmd.exe并执行一些命令?

如果是,那么我该如何做?

2个回答

6
使用Node的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上有许多与此主题相关的软件包。


6
在您的 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作为参数。

1
我还有一个问题。假设我们有以下文件结构: -electron(文件夹) ---main.js (当我们运行代码时) -test(文件夹) ---index.js如何从 main.js 运行 index.js (类似于 "node index.js")? - hadlog
1
解决方案在这里 - hadlog
1
嘿,一个问题,使用上述过程,我们可以并行运行多个进程吗?还是只能在第一个进程完全完成后才能运行下一个进程? - Rama Rao M
您可以同时生成多个进程。 - Bud Damyanov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接