import * as childProcess from 'child_process' import * as path from 'path' import { sleep } from '../../shared/utils/async.utils' export const startProductionServer = async (projectDir: string) => { const hostname = '127.0.0.1' let port = 0 const child = childProcess .fork( path.join(require.resolve('next/dist/server//lib/start-server.js')), [], { cwd: projectDir, stdio: 'pipe', env: { NODE_ENV: 'production', NEXT_PRIVATE_WORKER: '1', }, }, ) .on('error', (err) => { console.log(err as any) }) .on('message', (message) => { console.log(message) }) .on('exit', (code) => { console.log(code) }) child.stdout?.on('data', (data) => { const lines = (data.toString() || '').split('\n') if (port > 0) return for (const line of lines) { const match = line.match(/.*http:\/\/127\.0\.0\.1:(\d+)/) if (match) { port = parseInt(match[1], 10) } } }) child.stderr?.on('data', (data) => { console.error(data.toString()) }) child.send({ nextWorkerOptions: { port, hostname, isDev: false, dir: projectDir, }, }) while (port === 0) { await sleep(100) } return { hostname, port, } }