Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

dev.mjs

80 lines1.8 KB

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 })
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
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 }
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 }
76​
77run().catch((error) => {
78 console.error(error)
79 process.exitCode = 1
80})