Browse Source

更新调起外部程序的交互逻辑

master
Poised_flw 4 years ago
parent
commit
65383d3e11
  1. 22
      README.md
  2. 16
      app/main/child_process.js
  3. 19
      app/main/ipc.js

22
README.md

@ -7,20 +7,22 @@
```javascript
// 发起调用命令
window.api.send('spawn', {
command: '微信.exe',
command: 'ls',
args: null, // ['--disable-cache'] 多参数通过数组方式传递
key: + new Date, // 唯一key,用于推送后续执行结果时进行关联
options: {
onSuccess: data => {}, // 执行成功的回调,data为执行程序的输出
onError: err => {}, // 执行失败的回调
onClose: () => {}, // 关闭回调
}
})
// 接收执行结果
window.api.on('spawn-success', ({ pid, key }) => {
window.api.on('spawn-success', (event, { pid, key, data }) => {
// pid 为以上调起程序后的pid(用于后续主动kill)
// key 为调起时传递的key
// data 为执行程序的输出
})
// 执行异常
window.api.on('spawn-error', (event, { key, err }) => {
// key 为调起时传递的key
// err 为错误信息
})
// 主动关闭程序
@ -33,12 +35,12 @@ window.api.send('kill-process', [pid]);
```javascript
// 接收外部程序的消息,如openMap通道(具体的通道配置请参考ipc.js)
window.api.on('openMap', data => {
window.api.on('openMap', (event, data) => {
// data 为json格式
})
// 监听自定义通道,如custom-xxx(完全自定义,具体的名字可以和外部程序商量)
window.api.on('custom-xxx', data => {})
window.api.on('custom-xxx', (event, data) => {})
// 向外部程序推送消息
/**
@ -64,7 +66,7 @@ window.api.send('bridge', {
})
// 以上面的事件为例,在其他应用中监听该事件达到事件通信的目的
window.api.on('map-connection', data => {})
window.api.on('map-connection', (event, data) => {})
```
## 如何通过框架以新窗口的形式打开应用

16
app/main/child_process.js

@ -8,19 +8,23 @@ function start(command, args, options = {}) {
const childProgress = spawn(command, args)
pidMap[childProgress.pid] = childProgress
childProgress.stdout.on('data', data => {
options.onSuccess && options.onSuccess(data)
})
const promise = new Promise((resolve, reject) => {
childProgress.stdout.on('data', data => {
resolve(data.toString())
})
childProgress.stderr.on('data', data => {
options.onError && options.onError(data)
childProgress.stderr.on('data', data => {
reject(data.toString())
})
})
/**
childProgress.on('close', code => {
options.onClose && options.onClose(code)
})
*/
return childProgress.pid
return { pid: childProgress.pid, promise }
}
function kill(pid) {

19
app/main/ipc.js

@ -260,19 +260,26 @@ module.exports = () => {
command: '微信.exe',
args: null || ['--disable-cache'],
key: + new Date // 唯一key,用来做关闭识别,
options: {
onSuccess: data => {}, // 正常执行回调
onError: err => {}, // 错误执行回调
onClose: code => {}, // 关闭回调
}
})
*/
ipc.on('spawn', (event, arg) => {
const pid = childProcess.start(arg.command, arg.args, arg.options)
const { pid, promise } = childProcess.start(arg.command, arg.args, arg.key)
event.sender.send('spawn-success', {
key: arg.key,
pid
})
promise.then(data => {
event.sender.send('spawn-success', {
key: arg.key,
data
})
})
promise.catch(err => {
event.sender.send('spawn-error', {
key: arg.key,
err
})
})
})
// ipcRenderer.send('kill-process', [pid])

Loading…
Cancel
Save