Currently, I'm doing a code to monitor my files in a given directory and see when changes occur, in order to restart the server, the server is express, and it is running from another file, the server has been a sub -process, this is my code:
watcher.js
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var spawn = require('child_process').spawn;
const BASE_DIR = __dirname;
const ENCODING = 'utf8';
var child_server = spawn('node', ['${BASE_DIR}/main.js'], {stdio: [null, null, null, 'ipc']});
child_server.stdout.on('data', (data) => {
console.log(data.toString(ENCODING));
});
child_server.stderr.on('data', (data) => {
console.log('Traceback:\n');
console.log(data.toString(ENCODING));
});
child_server.on('exit', () => {
// aqui es donde trato volver a iniciar el proceso, pero no inicia
setTimeout(() => {
// console.log(child_server);
child_server = spawn('node', ['${BASE_DIR}/main.js'], {stdio: [null, null, null, 'ipc']});
}, 2000);
console.log('Restaring the server...');
});
fs.watch(BASE_DIR, {encoding: 'buffer', recursive: true}, (eventType, filename) => {
if (eventType == 'change' && filename) {
// child_server.kill('SIGHUP');
child_server.kill('SIGINT');
}
});
process.on('SIGINT', function() {
console.log("Caught interrupt signal");
child_server.kill();
process.exit();
});
process.on('uncaughtException', function(error) {
child_server.kill();
throw error;
});
It works almost well, that is, as soon as it is executed, it starts the server successfully, but when detecting the change, it kills the server process but does not restart it.
The question basically is how to properly restart a process with nodejs ?