I'm tryng to make a server with muitiple workers, but the server never starts when I use the import statment. If i put the code directly inside the worker function they run with no problems.
code with import:
import os from 'os'
import cluster from 'cluster'
import { initJobs } from './jobs'
import * as dotenv from 'dotenv'
import express from 'express'
import cors from 'cors'
import 'express-async-errors'
import http from 'http'
import routes from './routes/index.routes'
import { socket } from './socket'
import { startDatabase } from './db'
import errorCatcher from './errors'
dotenv.config()
import { logSuccess, logError } from './utils/log'
// initJobs(io)
const runPrimaryProcess = () => {
const processesCount = os.cpus().length
logSuccess('server', `Primary ${process.pid} is running`)
logSuccess('server', `Forking Server with ${processesCount} processes \n`)
for (let index = 0; index < processesCount; index++) cluster.fork()
cluster.on('exit', (worker, code, _signal) => {
if (code !== 0 && !worker.exitedAfterDisconnect) {
logError('cluster', `Worker ${worker.process.pid} died... scheduling another one!`)
cluster.fork()
}
})
}
const runWorkerProcess = async () => {
logSuccess('worker', `Worker ${process.pid} started`)
await import('./server')
}
cluster.isPrimary ? runPrimaryProcess() : runWorkerProcess()
server.ts:
import express from 'express'
import cors from 'cors'
import 'express-async-errors'
import http from 'http'
import routes from './routes/index.routes'
import { socket } from './socket'
import { startDatabase } from './db'
import { logSuccess } from './utils/log'
import errorCatcher from './errors'
// import { initJobs } from './jobs'
export const app = express()
app.use(cors())
app.use(express.json())
app.use(routes)
const server = http.createServer(app)
startDatabase()
const io = socket(server)
errorCatcher(app)
// initJobs(io)
const port = process.env.DEV_LOG_PORT || 3333
if (process.env.NODE_ENV !== 'test') {
server.listen(port, () => {
logSuccess('server', `started on port ${port} `)
})
}
all the works are instaced, showing the pid correctly, but server not start.(console.logs inside the server.ts does not show as well)
When I put the server.ts code inside runWorkerProcess function, all runs correctly.