Skip to content

Commit

Permalink
fix: properly shut down server
Browse files Browse the repository at this point in the history
  • Loading branch information
christian-bromann committed Jul 9, 2024
1 parent 06fc65c commit d5ca4ad
Showing 1 changed file with 21 additions and 21 deletions.
42 changes: 21 additions & 21 deletions src/launcher.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import path from 'node:path'
import url from 'node:url'
import cp from 'node:child_process'
import cp, { type ChildProcess } from 'node:child_process'

import logger from '@wdio/logger'
import getPort from 'get-port'
import type { NextServer } from 'next/dist/server/next.js'

import { pkg } from './constants.js'
import { lookupNextConfig } from './utils.js'
Expand All @@ -14,7 +13,7 @@ const log = logger('wdio-next-service')

export class NuxtServiceLauncher {
#options: Required<NextServiceOptions>
#server?: NextServer
#server?: ChildProcess

constructor (options: NextServiceOptions) {
log.info(`Initiate Next Service (v${pkg.version})`)
Expand Down Expand Up @@ -43,49 +42,50 @@ export class NuxtServiceLauncher {

log.info(`Start Next.js dev server on ${this.#options.hostname}:${port}`)
const startServerPath = import.meta.resolve('next/dist/server/lib/start-server.js')
const child = cp.fork(url.fileURLToPath(startServerPath), {
stdio: 'inherit',
cwd: path.dirname(nextjsConfigPath),
env: {
...process.env,
WDIO_NEXT_SERVICE: '1',
NEXT_PRIVATE_WORKER: '1'
}
})

await new Promise<void>((resolve) => {
let resolved = false
this.#server = cp.fork(url.fileURLToPath(startServerPath), {
stdio: 'inherit',
cwd: path.dirname(nextjsConfigPath),
env: {
...process.env,
WDIO_NEXT_SERVICE: '1',
NEXT_PRIVATE_WORKER: '1'
}
})

const nextWorkerOptions = {
port,
dir: path.dirname(nextjsConfigPath),
allowRetry: true,
isDev
}
child.on('message', (msg: any) => {

this.#server.on('message', (msg: any) => {
if (msg && typeof msg === 'object') {
if (msg.nextWorkerReady) {
child.send({ nextWorkerOptions })
if (msg.nextWorkerReady && this.#server) {
this.#server.send({ nextWorkerOptions })
} else if (msg.nextServerReady && !resolved) {
resolved = true
resolve()
}
}
})
child.on('error', (err) => {
this.#server.on('error', (err) => {
log.error('Failed to start Next.js server', err)
})
child.on('exit', (code, signal) => {
this.#server.on('exit', (code, signal) => {
log.info(`Next.js dev server stopped with exit code ${code} and signal ${signal}`)
})
})

process.env.WDIO_BASE_URL = `http://${this.#options.hostname}:${port}`
}

public async onComplete () {
log.info('Stop Next.js dev server')
public onComplete () {
if (this.#server) {
await this.#server.close()
log.info('Stop Next.js dev server')
this.#server.kill()
}
}
}

0 comments on commit d5ca4ad

Please sign in to comment.