Open History to see the last commit
1import { spawn } from 'node:child_process'
2import { once } from 'node:events'
3import { API_PORT } from '../config/ports.js'
4β
5const viteCommand = process.platform === 'win32' ? 'vite.cmd' : 'vite'
6const cwd = new URL('..', import.meta.url)
7β
8function forwardOutput(prefix, stream, output) {
9 stream.on('data', (chunk) => {
10 output.write(`${prefix}${chunk}`)
11 })
12}
13β
14function start(name, command, args, extraEnv = {}) {
15 const child = spawn(command, args, {
16 cwd,
17 stdio: ['ignore', 'pipe', 'pipe'],
18 env: {
19 ...process.env,
20 ...extraEnv,
21 },
22 })
23β
24 forwardOutput(`[${name}] `, child.stdout, process.stdout)
25 forwardOutput(`[${name}] `, child.stderr, process.stderr)
26β
27 return child
28}
29β
30async function stop(child) {
31 if (!child || child.exitCode !== null) {
32 return
33 }
34β
35 child.kill('SIGTERM')
36 await Promise.race([
37 once(child, 'exit'),
38 new Promise((resolve) => setTimeout(resolve, 2000)),
39 ])
40β
41 if (child.exitCode === null) {
42 child.kill('SIGKILL')
43 await Promise.race([
44 once(child, 'exit'),
45 new Promise((resolve) => setTimeout(resolve, 2000)),
46 ])
47 }
48}
49β
50async function run() {
51 const api = start('api', process.execPath, ['./server/index.mjs'])
52 const web = start('web', viteCommand, [], {
53 VITE_PAGINATION_API_PORT: String(API_PORT),
54 })
55β
56 const shutdown = async () => {
57 await Promise.all([stop(web), stop(api)])
58 }
59β
60 process.on('SIGINT', shutdown)
61 process.on('SIGTERM', shutdown)
62β
63 const [winner] = await Promise.race([
64 once(api, 'exit').then(([code]) => ({ name: 'api', code })),
65 once(web, 'exit').then(([code]) => ({ name: 'web', code })),
66 ])
67β
68 await shutdown()
69β
70 if (winner.code !== 0 && winner.code !== null) {
71 process.exitCode = winner.code
72 } else {
73 process.exitCode = 1
74 }
75}
76β
77run().catch((error) => {
78 console.error(error)
79 process.exitCode = 1
80})