NodeJS and Forever (monitoring and restarting app)

2019-05-06 14:40发布

问题:

I'm trying to setup forever and NodeJS to monitor&restart my app and also keep it running when exits. Currently I have this:

var forever = require("forever-monitor");

var child = new(forever.Monitor)('main.js', {
    'silent': false,
    'pidFile': '../pids/app.pid',
    'sourceDir': '.',
    'watch': true,
    'watchDirectory': '.',
    'watchIgnoreDotFiles': null,
    'watchIgnorePatterns': null,
    'logFile': '../logs/forever.log',
    'outFile': '../logs/forever.out',
    'errFile': '../logs/forever.err'
});

child.start();

Which starts my app just fine but it doesn't restart it when I make changes in the file. Is there some option that I'm missing?

EDIT: After digging into the problem I found that the file change is detected actually, it's just that the process isn't restarted. I'm looking at line ~317 - Monitor.prototype.kill (in monitor.js) but everything looks like it should work.

EDIT: I managed to fix the issue. It's a bug in the library's code. Check here: https://github.com/nodejitsu/forever-monitor/issues/27

回答1:

nodemon and forever are a pain to get running consistently. I would try using a shell script first. If you are on linux, just place a monitornode file in /etc/cron.d

*/1 * * * * root  /var/www/nodejs/monitornode.sh

and have a script somewhere on your machine

Try this if you are getting started, create a file /var/www/nodejs/monitornode.sh and chmod +x :

#!/bin/sh

TT_NODE="node /var/www/nodejs/node.js"

# NODEJS Watcher
if [ -z `pgrep -f -x "$TT_NODE"` ] 
then
    echo "Starting $TT_NODE."
    cmdNODE="$TT_NODE >> /var/www/logs/node.log &"
    eval $cmdNODE
fi


回答2:

Check out the nodemon package to do the whole "reload on file change" thing.