showing results for - "electron js execute command"
Emmanuelle
17 Apr 2016
1//Uses node.js process manager
2const electron = require('electron');
3const child_process = require('child_process');
4const dialog = electron.dialog;
5
6// This function will output the lines from the script 
7// and will return the full combined output
8// as well as exit code when it's done (using the callback).
9function run_script(command, args, callback) {
10    var child = child_process.spawn(command, args, {
11        encoding: 'utf8',
12        shell: true
13    });
14    // You can also use a variable to save the output for when the script closes later
15    child.on('error', (error) => {
16        dialog.showMessageBox({
17            title: 'Title',
18            type: 'warning',
19            message: 'Error occured.\r\n' + error
20        });
21    });
22
23    child.stdout.setEncoding('utf8');
24    child.stdout.on('data', (data) => {
25        //Here is the output
26        data=data.toString();   
27        console.log(data);      
28    });
29
30    child.stderr.setEncoding('utf8');
31    child.stderr.on('data', (data) => {
32        // Return some data to the renderer process with the mainprocess-response ID
33        mainWindow.webContents.send('mainprocess-response', data);
34        //Here is the output from the command
35        console.log(data);  
36    });
37
38    child.on('close', (code) => {
39        //Here you can get the exit code of the script  
40        switch (code) {
41            case 0:
42                dialog.showMessageBox({
43                    title: 'Title',
44                    type: 'info',
45                    message: 'End process.\r\n'
46                });
47                break;
48        }
49
50    });
51    if (typeof callback === 'function')
52        callback();
53}
54