diff --git a/README.md b/README.md index b9186f96..59afb8cd 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 49a08542..7933ad42 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) {