Skip to content

Instantly share code, notes, and snippets.

@andreciornavei
Last active May 14, 2022 19:58
Show Gist options
  • Select an option

  • Save andreciornavei/a481c1e9e4164ff03fb616006214bd63 to your computer and use it in GitHub Desktop.

Select an option

Save andreciornavei/a481c1e9e4164ff03fb616006214bd63 to your computer and use it in GitHub Desktop.
Resilient NodeJS Server
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();
'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