Running a Node.js Daemon with Fastify (No PM2, No systemd)
Every few months someone on Reddit asks "how do I run a Node.js process in the background." The answers are always PM2, forever, or systemd. All fine. But if you're shipping a CLI tool that users i...

Source: DEV Community
Every few months someone on Reddit asks "how do I run a Node.js process in the background." The answers are always PM2, forever, or systemd. All fine. But if you're shipping a CLI tool that users install on their own machines, you can't assume any of those exist. I have a CLI that starts a local HTTP daemon. my-tool start forks into the background, user closes their terminal, daemon keeps running. About 700 lines for the whole thing, 150 of which are just the fork/PID/signal plumbing. Fastify 5 for the HTTP layer. Fork, detach, forget import { fork } from "node:child_process"; import * as fs from "node:fs"; import * as path from "node:path"; import * as os from "node:os"; const DATA_DIR = path.join(os.homedir(), ".my-tool"); const LOG_PATH = path.join(DATA_DIR, "daemon.log"); function startDaemon(): void { fs.mkdirSync(DATA_DIR, { recursive: true }); const logFd = fs.openSync(LOG_PATH, "a"); const child = fork(__filename, ["start", "--_daemon"], { detached: true, stdio: ["ignore", logF