run.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * 在本目录启动 exe,若有报错则写入 启动报错.txt
  3. * 用法:node run.js 或双击 run.bat
  4. */
  5. const path = require('path')
  6. const fs = require('fs')
  7. const { spawn } = require('child_process')
  8. const dir = __dirname
  9. const errorLogPath = path.join(dir, '启动报错.txt')
  10. const exeNames = ['AndroidRemoteController.exe', 'electron-react-vite-app.exe']
  11. let exePath = null
  12. for (const name of exeNames) {
  13. const p = path.join(dir, name)
  14. if (fs.existsSync(p)) {
  15. exePath = p
  16. break
  17. }
  18. }
  19. if (!exePath) {
  20. const msg = `[${new Date().toISOString()}] 未找到 exe(${exeNames.join(' / ')})
  21. `
  22. fs.writeFileSync(errorLogPath, msg, 'utf8')
  23. console.error(msg.trim())
  24. process.exit(1)
  25. }
  26. const chunks = []
  27. function writeErrorLog(extra) {
  28. const header = `[${new Date().toISOString()}] 运行 ${path.basename(exePath)} 异常
  29. `
  30. const body = chunks.length ? Buffer.concat(chunks).toString('utf8') : ''
  31. const tail = extra ? `
  32. ${extra}` : ''
  33. fs.writeFileSync(errorLogPath, header + body + tail, 'utf8')
  34. }
  35. const child = spawn(exePath, [], {
  36. cwd: dir,
  37. stdio: ['ignore', 'pipe', 'pipe'],
  38. windowsHide: false
  39. })
  40. child.stdout.on('data', (data) => {
  41. process.stdout.write(data)
  42. })
  43. child.stderr.on('data', (data) => {
  44. chunks.push(data)
  45. process.stderr.write(data)
  46. })
  47. child.on('error', (err) => {
  48. writeErrorLog(`进程启动失败: ${err.message}`)
  49. console.error(err)
  50. process.exit(1)
  51. })
  52. child.on('exit', (code, signal) => {
  53. if (code !== 0 && code != null) {
  54. writeErrorLog(`退出码: ${code}${signal ? ` 信号: ${signal}` : ''}`)
  55. }
  56. })