Skip to content

Commit c907a8c

Browse files
committed
chore: shutdown server better
1 parent 54b1d40 commit c907a8c

File tree

1 file changed

+33
-16
lines changed

1 file changed

+33
-16
lines changed

scripts/build.js

Lines changed: 33 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,24 @@
1-
const { exec } = require('child_process');
1+
const { spawn } = require('child_process');
22
const fs = require('fs');
33

4-
// Function to run a shell command
5-
function runCommand(command) {
6-
return new Promise((resolve, reject) => {
7-
const process = exec(command);
4+
// Function to run a shell command and return the process immediately
5+
function runCommand(command, args = []) {
6+
const process = spawn(command, args);
87

9-
process.stdout.on('data', (data) => {
10-
console.log(data);
11-
});
8+
process.stdout.on('data', (data) => {
9+
console.log(data.toString());
10+
});
1211

13-
process.stderr.on('data', (data) => {
14-
console.error(data);
15-
});
12+
process.stderr.on('data', (data) => {
13+
console.error(data.toString());
14+
});
15+
return process;
16+
}
17+
18+
// Function to run a shell command and wait for it to complete
19+
function runCommandAndWait(command, args = []) {
20+
return new Promise((resolve, reject) => {
21+
const process = runCommand(command, args);
1622

1723
process.on('close', (code) => {
1824
if (code === 0) {
@@ -21,6 +27,10 @@ function runCommand(command) {
2127
reject(`Command failed with code ${code}`);
2228
}
2329
});
30+
31+
process.on('error', (error) => {
32+
reject(`Command failed with error ${error}`);
33+
});
2434
});
2535
}
2636

@@ -65,10 +75,15 @@ async function main() {
6575
}
6676

6777
try {
68-
console.log('Starting server...');
69-
runCommand('nx serve api');
78+
console.log('Build server...');
79+
await runCommandAndWait('nx', ['build', 'api']);
7080

71-
console.log(`Waiting for server to be ready on port ${port}...`);
81+
console.log('Server build completed. Starting server...');
82+
const apiProcess = runCommand('node', ['dist/apps/api/main.js']);
83+
84+
console.log(
85+
`Waiting for server ${apiProcess.pid} to be ready on port ${port}...`,
86+
);
7287
await waitForServer(port);
7388

7489
console.log('Server is ready. Fetching routes...');
@@ -77,10 +92,12 @@ async function main() {
7792
console.log('Routes saved to routes.txt');
7893

7994
console.log('Building app...');
80-
await runCommand('nx build app');
81-
95+
await runCommandAndWait('nx', ['build', 'app']);
8296
console.log('App build completed');
8397

98+
console.log('Stopping server...');
99+
apiProcess.kill('SIGINT');
100+
84101
process.exit(0);
85102
} catch (error) {
86103
console.error(`Error: ${error}`);

0 commit comments

Comments
 (0)