From a724e538aca7fca62aa7901ada50353876c70b6e Mon Sep 17 00:00:00 2001 From: acceptable Date: Thu, 14 Jun 2018 20:28:47 +1000 Subject: [PATCH] docs: more docs for nodemon as child process (#1362) I was trying to find out how to use nodemon as child process, and stumble upon this https://github.com/remy/nodemon/issues/1018 So adding more docs for other people later to make it clearer how to do it. [skip ci] --- README.md | 4 ++++ doc/events.md | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/README.md b/README.md index b9186f9..59afb8c 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,10 @@ Note that if you specify a `--config` file or provide a local `nodemon.json` any Please see [doc/requireable.md](doc/requireable.md) +## Using nodemon as child process + +Please see [doc/events.md](doc/events.md#Using_nodemon_as_child_process) + ## Running non-node scripts nodemon can also be used to execute and monitor other programs. nodemon will read the file extension of the script being run and monitor that extension instead of .js if there's no `nodemon.json`: diff --git a/doc/events.md b/doc/events.md index 49a0854..7933ad4 100644 --- a/doc/events.md +++ b/doc/events.md @@ -47,11 +47,29 @@ nodemon.emit('restart'); nodemon.emit('quit'); ``` +## Using nodemon as child process + If nodemon is a spawned process, then the child (nodemon) will emit message events whereby the event argument contains the event type, and instead of emitting events, you `send` the command: ```js +// using `spawn` as example, can use other functions like `fork`, etc +// https://nodejs.org/api/child_process.html +const { spawn } = require('child_process'); + +function spawnNodemon() { + const cp = spawn('nodemon', ['path/to/file.js', '--watch', 'path/to/watch'], { + // the important part is the 4th option 'ipc' + // this way `process.send` will be available in the child process (nodemon) + // so it can communicate back with parent process (through `.on()`, `.send()`) + // https://nodejs.org/api/child_process.html#child_process_options_stdio + stdio: ['pipe', 'pipe', 'pipe', 'ipc'], + }); + + return cp; +} + var app = spawnNodemon(); app.on('message', function (event) {