ipcMain.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. const { ipcMain: ipc } = require('electron')
  2. const path = require('path')
  3. const fs = require('fs')
  4. const _ = require('lodash');
  5. /**
  6. * 发送响应信息给渲染进程
  7. * @param event
  8. * @param channel
  9. * @param data
  10. * @private
  11. */
  12. const _echo = (event, channel, data) => {
  13. console.log('[ipc] [answerRenderer] result: ', {channel, data})
  14. event.reply(`${channel}`, data)
  15. }
  16. /**
  17. * 执行主进程函数,并响应渲染进程
  18. * @param channel
  19. * @param callback
  20. */
  21. const answerRenderer = (channel, callback) => {
  22. ipc.on(channel, async (event, param) => {
  23. const result = await callback(event, channel, param)
  24. _echo(event, channel, result)
  25. })
  26. }
  27. /**
  28. * get api method name
  29. * ex.) jsname='user' method='get' => 'user.get'
  30. * @param {String} jsname
  31. * @param {String} method
  32. */
  33. const getApiName = (jsname, method) => {
  34. return jsname + '.' + method;
  35. }
  36. /**
  37. * 加载所有的主程序
  38. */
  39. exports.setup = () => {
  40. console.log('[electron-lib-ipc] [setup]');
  41. const ipcDir = path.normalize(__dirname + '/../ipc');
  42. fs.readdirSync(ipcDir).forEach(function (filename) {
  43. if (path.extname(filename) === '.js' && filename !== 'index.js') {
  44. const name = path.basename(filename, '.js');
  45. const fileObj = require(`../ipc/${filename}`);
  46. _.map(fileObj, function(fn, method) {
  47. let methodName = getApiName(name, method);
  48. answerRenderer(methodName, fn);
  49. });
  50. }
  51. })
  52. }