node.js – How to launch a detached child process in Node, and reuse it on subsequent executions if already running?


I want to write a Node CLI that leaves a server/daemon running in the background, so subsequent calls to the CLI are much faster, as it can just print the latest info from the daemon (which is already primed with info as it’s been watching the filesystem).

My purpose is not type-checking, but the CLI architecture I want is similar to how flow seems to work: to be able to launch the background service if it’s not running (unique for the current working directory), or find the existing Node process if it’s already running, and communicate with it either way. Looking at how flow-bin is set up in my local node_modules, it seems to ship with binaries (>20MB each) for the three main platforms (which I guess are all compiled from OCaml?). The flow CLI entry point is actually a tiny Node bin script which just spawns the relevant binary for the current platform. So I guess somehow the binary itself checks for an already-running instance of itself, and shuts itself down if found…? But I’m not sure how that could work, as it would need to still print something to stdout.

Can anyone shed any light on the architecture I want – basically, launching a detached child process from a parent Node process, and then reusing the same child process on subsequent executions of the parent? Are there any other open source examples I could look at, preferably just using plain Node JavaScript instead of OCaml?