forked from freeCodeCamp/contribute
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run-server.mjs
64 lines (56 loc) · 1.76 KB
/
run-server.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import express from 'express';
import morgan from 'morgan';
import winston from 'winston';
import { handler as ssrHandler } from './dist/server/entry.mjs';
const app = express();
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.colorize(),
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
winston.format.printf(({ timestamp, level, message }) => {
return `${timestamp} [${level}] ${message}`;
})
),
transports: [new winston.transports.Console()]
});
const morganStream = {
write: message => logger.info(message.trim())
};
app.use(morgan('tiny', { stream: morganStream }));
// Change this based on your astro.config.mjs, `base` option.
// They should match. The default value is "/".
const base = '/';
app.use(base, express.static('dist/client/'));
app.use(ssrHandler);
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
logger.info(`Server is running on port ${PORT}`);
});
// Handle server errors
server.on('error', error => {
logger.error(`Server error: ${error.message}`, { error });
process.exit(1);
});
// Graceful shutdown
const gracefulShutdown = signal => {
logger.info(`Received ${signal}. Shutting down gracefully...`);
server.close(err => {
if (err) {
logger.error('Error during shutdown', { error: err });
process.exit(1);
} else {
logger.info('Closed out remaining connections.');
process.exit(0);
}
});
// Forcefully shut down after 10 seconds
setTimeout(() => {
logger.error(
'Could not close connections in time, forcefully shutting down'
);
process.exit(1);
}, 10000);
};
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));