doc/events.md
nodemon will emit events based on the child process.
Note that if you want to supress the normal stdout & stderr of the child, in favour
of processing the stream manually using the stdout/stderr nodemon events, pass
nodemon the option of stdout: false.
If nodemon is required, events can be bound and emitted on the nodemon object:
var nodemon = require('nodemon');
nodemon({ script: 'app.js' }).on('start', function () {
console.log('nodemon started');
}).on('crash', function () {
console.log('script crashed for some reason');
});
// force a restart
nodemon.emit('restart');
// force a quit
nodemon.emit('quit');
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:
// 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) {
if (event.type === 'start') {
console.log('nodemon started');
} else if (event.type === 'crash') {
console.log('script crashed for some reason');
}
});
// force a restart
app.send('restart');
// force a quit
app.send('quit');
Note that even though the child will still emit a message event whose type is
exit, it makes more sense to listen to the actual exit event on the child:
app.on('exit', function () {
console.log('nodemon quit');
});