Skip to content

Commit

Permalink
🚀 feat(cli-wrapper.ts): add wrapper for CLI entrypoint to enable rest…
Browse files Browse the repository at this point in the history
…artable process

The `cli-wrapper.ts` file is added to wrap the CLI entrypoint in a restartable process. This is done to enable the application to be restarted without having to manually stop and start the process. The wrapper is only enabled for the `nuxt dev` command. The wrapper starts a subprocess and listens for messages from the child process. If the child process sends a `nuxt:restart` message, the subprocess is killed and a new subprocess is started.
  • Loading branch information
nyxb committed May 19, 2023
1 parent da1f0b5 commit c16d014
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
2 changes: 1 addition & 1 deletion bin/nyxbi.mjs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
#!/usr/bin/env node
import('../dist/cli-run.mjs')
import('../dist/cli-wrapper.mjs')
47 changes: 47 additions & 0 deletions src/cli-wrapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* This file is used to wrap the CLI entrypoint in a restartable process.
*/
import { fileURLToPath } from 'node:url'
import { fork } from 'node:child_process'
import type { ChildProcess } from 'node:child_process'

const cliEntry = new URL('../dist/cli-run.mjs', import.meta.url)

// Only enable wrapper for nuxt dev command
if (process.argv[2] === 'dev') {
process.env.__CLI_ARGV__ = JSON.stringify(process.argv)
startSubprocess()
}
else {
import(cliEntry.href)
}

function startSubprocess() {
let childProc: ChildProcess | undefined

const onShutdown = () => {
if (childProc) {
childProc.kill()
childProc = undefined
}
}

process.on('exit', onShutdown)
process.on('SIGTERM', onShutdown) // Graceful shutdown
process.on('SIGINT', onShutdown) // Ctrl-C
process.on('SIGQUIT', onShutdown) // Ctrl-\

start()

function start() {
childProc = fork(fileURLToPath(cliEntry))
// eslint-disable-next-line curly
childProc.on('close', (code) => { if (code) { process.exit(code) } })
childProc.on('message', (message) => {
if ((message as { type: string })?.type === 'nuxt:restart') {
childProc?.kill()
startSubprocess()
}
})
}
}

0 comments on commit c16d014

Please sign in to comment.