In a recent project, electron is needed to start the background service, which is an exe program with a directory one layer above the directory packed by electron
First through the APP to obtain the path of the program
import { app, BrowserWindow } from 'electron'
// Directory where the current executable resides
let appPath = app.getPath('exe')
// Get the directory app at the next level
let path = appPath.replace(/\\app\\studio.exe/.' ')
Copy the code
CMD is then invoked via Node’s child_process
const exec = require('child_process'Exec // Name of the background service that needs to be started locallylet cmdStr = 'server'
let cmdPath = path
let workerProcess
function runExec() {// Execute the command line, if the command does not need a path, or is the project root directory, do not need the CWD parameter: workerProcess =exec(cmdStr, {CWD: cmdPath}) {} : workerProcess = {} : workerProcess = {} : workerProcess =exec(cmdStr, {}) // Print normal background executable output workerprocess.stdout.on ('data'.function (data) {
console.log('stdout: '+ data)}) // Print error background executable output workerprocess.stderr.on ('data'.function (data) {
console.log('stderr: '+ data)}) workerprocess.on ('close'.function (code) {
console.log('out code: + code)
})
}
Copy the code
Need to be called in electron’s Ready life cycle
app.on('ready'.function(){
runExec()
})
Copy the code
That’s it, isn’t it? It’s easy