-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
67 lines (60 loc) · 1.86 KB
/
Copy pathserver.js
File metadata and controls
67 lines (60 loc) · 1.86 KB
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
65
66
67
import { createServer as createHttpServer } from "node:http";
import { dirname, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { createApp } from "./src/app.js";
import { loadConfig } from "./src/config.js";
import { LinkStore } from "./src/store.js";
const defaultRootDir = dirname(fileURLToPath(import.meta.url));
export async function startServer({
rootDir = defaultRootDir,
env = process.env,
} = {}) {
const config = await loadConfig({ rootDir, env });
const store = new LinkStore(config.dataDir);
await store.load();
const app = createApp({
config,
store,
publicDir: join(rootDir, "public"),
});
const server = createHttpServer(app);
await new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(config.port, config.host, resolve);
});
const address = server.address();
const port = typeof address === "object" ? address.port : config.port;
console.log(`LinkBoard running at http://${config.host}:${port}`);
return {
config,
server,
store,
async close() {
await new Promise((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
await store.flush();
},
};
}
function installShutdown(runtime) {
for (const signal of ["SIGINT", "SIGTERM"]) {
process.once(signal, async () => {
console.log(`${signal} received; shutting down`);
const forceExit = setTimeout(() => process.exit(1), 10_000);
forceExit.unref();
try {
await runtime.close();
process.exitCode = 0;
} catch (error) {
console.error("Graceful shutdown failed", error);
process.exitCode = 1;
}
});
}
}
const isEntryPoint =
process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url;
if (isEntryPoint) {
installShutdown(await startServer());
}