electron js execute js file code example
Example 1: electron js execute command
const electron = require('electron');
const child_process = require('child_process');
const dialog = electron.dialog;
function run_script(command, args, callback) {
var child = child_process.spawn(command, args, {
encoding: 'utf8',
shell: true
});
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) => {
data=data.toString();
console.log(data);
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', (data) => {
mainWindow.webContents.send('mainprocess-response', data);
console.log(data);
});
child.on('close', (code) => {
switch (code) {
case 0:
dialog.showMessageBox({
title: 'Title',
type: 'info',
message: 'End process.\r\n'
});
break;
}
});
if (typeof callback === 'function')
callback();
}
Example 2: how to run a js file in node
Save your .js file in the same folder as node.js,
For windows , Usually location is- "C:\Program Files\nodejs"
Open 'Command prompt and locate node.js folder' OR directly open 'Node.js command prompt' and type
>> node (file_name).js
Example 3: javascript running at node
const inNode = new Function('try{return this===global;}catch(err){return false;}')();