run-process.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/env node
  2. /**
  3. * run-process.js
  4. * 接收两个参数:ip 数组 (JSON)、脚本名
  5. * 异步根据每个 ip 执行脚本
  6. *
  7. * 调用示例:node run-process.js '["192.168.2.5","192.168.2.6"]' 'RedNoteAIThumbsUp'
  8. */
  9. const path = require('path')
  10. const fs = require('fs')
  11. const { parseWorkflow, executeActionSequence } = require('./ef-compiler/ef-compiler.js')
  12. const ipListJson = process.argv[2]
  13. const scriptName = process.argv[3]
  14. const ipList = JSON.parse(ipListJson)
  15. let shouldStop = false
  16. const folderPath = path.join(path.resolve(__dirname, '..', 'static'), 'process', scriptName)
  17. const { actions } = parseWorkflow(JSON.parse(fs.readFileSync(path.join(folderPath, 'process.json'), 'utf8')))
  18. const resolution = { width: 1080, height: 1920 }
  19. /** 启动执行:遍历 ip 列表并异步执行脚本;任一台失败则停止全部并返回失败设备 IP */
  20. async function start() {
  21. let failedIp = null
  22. const runOne = async (ip) => {
  23. if (shouldStop) return { ip, success: false, stopped: true }
  24. const result = await executeActionSequence(actions, `${ip}:5555`, folderPath, resolution, 1000, null, () => shouldStop)
  25. if (!result.success) {
  26. if (!failedIp) { failedIp = ip; shouldStop = true }
  27. }
  28. return { ip, success: result.success }
  29. }
  30. const results = await Promise.all(ipList.map(ip => runOne(ip)))
  31. const output = failedIp
  32. ? { success: false, failedIp, results }
  33. : { success: true, results }
  34. process.stdout.write(JSON.stringify(output) + '\n')
  35. process.exit(failedIp ? 1 : 0)
  36. }
  37. /** 停止执行(SIGTERM/SIGINT 时调用) */
  38. function stop() {
  39. shouldStop = true
  40. }
  41. process.on('SIGTERM', () => { stop(); process.exit(130) })
  42. process.on('SIGINT', () => { stop(); process.exit(130) })
  43. start()