Skip to content

Instantly share code, notes, and snippets.

@gseok
Created June 22, 2020 00:25
Show Gist options
  • Save gseok/0837cd19b38b3b6ded24d48a7a49f522 to your computer and use it in GitHub Desktop.
Save gseok/0837cd19b38b3b6ded24d48a7a49f522 to your computer and use it in GitHub Desktop.
Simple Node forever code
#!/usr/bin/env node
const spawn = require('child_process').spawn;
const cmd = process.argv.shift(); // node cmd path
const args = ['./bin/www'];
// server starter is exit then exit all
let ps = null;
function killChildProcess() {
if (ps) {
ps.kill();
ps = null;
}
}
process.on('exit', function() {
console.log('Server starter exit');
if (ps) ps.kill();
});
process.on('SIGINT', function() {
process.exit();
});
(function main() {
console.log(`Sever starter pid: ${process.pid}`);
console.log(`Sever start command: ${cmd} ${args.toString()}`);
killChildProcess();
ps = spawn(cmd, args, {
cwd: process.cwd(),
detached: true,
stdio: 'inherit',
});
console.log(`Server pid: ${ps.pid}`);
// server forever start!
ps.on('exit', function() {
console.log('Server exit by unknown problem, retry server start');
killChildProcess();
setTimeout(main, 1000);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment