Last active
May 14, 2022 19:58
-
-
Save andreciornavei/a481c1e9e4164ff03fb616006214bd63 to your computer and use it in GitHub Desktop.
Resilient NodeJS Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as os from "os" | |
| import * as cluster from "cluster" | |
| import { bootstrap } from "./server" | |
| const numCpus = os.cpus().length | |
| const handleFork = () => { | |
| const worker = cluster.fork() | |
| worker.addListener("exit", (code) => { | |
| if (code !== 0) handleFork() | |
| }) | |
| } | |
| const main = () => { | |
| for (let i = 0; i < numCpus; i++) handleFork() | |
| } | |
| const worker = () => bootstrap() | |
| cluster.isMaster ? main() : worker(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use strict' | |
| import * as http from "http" | |
| const PORT = process.env.PORT || 1337 | |
| export const bootstrap = () => { | |
| const server = http.createServer((req, res) => { | |
| res.writeHead(200, { "Content-Type": "text/json" }) | |
| return res.end(JSON.stringify({ message: "Hello World" })) | |
| }) | |
| server.listen(PORT) | |
| server.once("listening", () => { | |
| console.log(`server starting on ${PORT} with process id ${process.pid}`) | |
| }) | |
| process.on('SIGINT', () => { | |
| console.log(`${process.pid} server process ending`, new Date().toISOString()) | |
| server.close(() => process.exit()) | |
| }) | |
| process.on('SIGTERM', () => { | |
| console.log(`${process.pid} server process ending`, new Date().toISOString()) | |
| server.close(() => process.exit()) | |
| }) | |
| process.on('uncaughtException', (error) => { | |
| console.error(`unhandledRejection happened: ${error.stack || error}`) | |
| }) | |
| process.on('unhandledRejection', (error) => { | |
| console.error(`unhandledRejection happened: ${error.stack || error}`) | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment