Code Monkey home page Code Monkey logo

forever-monitor's Introduction

forever-monitor Build Status

The core monitoring functionality of forever without the CLI

Usage

You can also use forever from inside your own Node.js code:

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

  var child = new (forever.Monitor)('your-filename.js', {
    max: 3,
    silent: true,
    args: []
  });

  child.on('exit', function () {
    console.log('your-filename.js has exited after 3 restarts');
  });

  child.start();

Spawning a non-node process

You can spawn non-node processes too. Either set the command key in the options hash or pass in an Array in place of the file argument like this:

  var forever = require('forever-monitor');
  var child = forever.start([ 'perl', '-le', 'print "moo"' ], {
    max : 1,
    silent : true
  });

Options available when using Forever in node.js

There are several options that you should be aware of when using forever. Most of this configuration is optional.

  {
    //
    // Basic configuration options
    //
    'silent': false,            // Silences the output from stdout and stderr in the parent process
    'uid': 'your-UID',          // Custom uid for this forever process. (default: autogen)
    'pidFile': 'path/to/a.pid', // Path to put pid information for the process(es) started
    'max': 10,                  // Sets the maximum number of times a given script should run
    'killTree': true,           // Kills the entire child process tree on `exit`

    //
    // These options control how quickly forever restarts a child process
    // as well as when to kill a "spinning" process
    //
    'minUptime': 2000,     // Minimum time a child process has to be up. Forever will 'exit' otherwise.
    'spinSleepTime': 1000, // Interval between restarts if a child is spinning (i.e. alive < minUptime).

    //
    // Command to spawn as well as options and other vars
    // (env, cwd, etc) to pass along
    //
    'command': 'perl',         // Binary to run (default: 'node')
    'args':    ['foo','bar'],  // Additional arguments to pass to the script,
    'sourceDir': 'script/path',// Directory that the source script is in

    //
    // Options for restarting on watched files.
    //
    'watch': true,               // Value indicating if we should watch files.
    'watchIgnoreDotFiles': null, // Whether to ignore file starting with a '.'
    'watchIgnorePatterns': null, // Ignore patterns to use when watching files.
    'watchDirectory': null,      // Top-level directory to watch from. You can provide multiple watchDirectory options to watch multiple directories (e.g. for cli: forever start -w='app' -w='some_other_directory' app\index.js)

    //
    // All or nothing options passed along to `child_process.spawn`.
    //
    'spawnWith': {
      customFds: [-1, -1, -1], // that forever spawns.
      setsid: false,
      uid: 0,      // Custom UID
      gid: 0,      // Custom GID
      shell: false // Windows only - makes forever spawn in a shell
    },

    //
    // More specific options to pass along to `child_process.spawn` which
    // will override anything passed to the `spawnWith` option
    //
    'env': { 'ADDITIONAL': 'CHILD ENV VARS' },
    'cwd': '/path/to/child/working/directory',

    //
    // Log files and associated logging options for this instance
    //
    'logFile': 'path/to/file', // Path to log output from forever process (when daemonized)
    'outFile': 'path/to/file', // Path to log output from child stdout
    'errFile': 'path/to/file', // Path to log output from child stderr

    //
    // ### function parseCommand (command, args)
    // #### @command {String} Command string to parse
    // #### @args    {Array}  Additional default arguments
    //
    // Returns the `command` and the `args` parsed from
    // any command. Use this to modify the default parsing
    // done by 'forever-monitor' around spaces.
    //
    'parser': function (command, args) {
      return {
        command: command,
        args:    args
      };
    }
  }

Events available when using an instance of Forever in node.js

Each forever object is an instance of the Node.js core EventEmitter. There are several core events that you can listen for:

  • error [err]: Raised when an error occurs
  • start [process, data]: Raised when the target script is first started.
  • stop [process]: Raised when the target script is stopped by the user
  • restart [forever]: Raised each time the target script is restarted
  • exit [forever]: Raised when the target script actually exits (permanently).
  • stdout [data]: Raised when data is received from the child process' stdout
  • stderr [data]: Raised when data is received from the child process' stderr

Typical console output

When running the forever CLI tool, it produces debug outputs about which files have changed / how processes exited / etc. To get a similar behaviour with forever-monitor, add the following event listeners:

const child = new (forever.Monitor)('your-filename.js');

child.on('watch:restart', function(info) {
    console.error('Restarting script because ' + info.file + ' changed');
});

child.on('restart', function() {
    console.error('Forever restarting script for ' + child.times + ' time');
});

child.on('exit:code', function(code) {
    console.error('Forever detected script exited with code ' + code);
});

Installation

  $ npm install forever-monitor

Run Tests

  $ npm test

License: MIT

forever-monitor's People

Contributors

abueckermb avatar alex7071 avatar atomizer avatar avianflu avatar darobin avatar ddelazerda avatar denysoblohin-okta avatar dermidgen avatar edef1c avatar estliberitas avatar ffflorian avatar indexzero avatar jcrugzz avatar jmav avatar julianduque avatar kibertoad avatar lucioperca avatar mmalecki avatar msokk avatar outbounder avatar paulmillr avatar pdehaan avatar ritch avatar rprieto avatar ryanramage avatar shenanigans avatar smoodiver avatar thomasr avatar tjatse avatar yobretaw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

forever-monitor's Issues

Error: write after end at writeAfterEnd (_stream_writable.js:125:12)

I have next error:

stream.js:94
      throw er; // Unhandled stream error in pipe.
            ^
Error: write after end
    at writeAfterEnd (_stream_writable.js:125:12)
    at WriteStream.Writable.write (_stream_writable.js:170:5)
    at Socket.ondata (stream.js:51:26)
    at Socket.EventEmitter.emit (events.js:117:20)
    at Socket.<anonymous> (_stream_readable.js:710:14)
    at Socket.EventEmitter.emit (events.js:92:17)
    at emitReadable_ (_stream_readable.js:382:10)
    at emitReadable (_stream_readable.js:378:5)
    at readableAddChunk (_stream_readable.js:143:7)
    at Socket.Readable.push (_stream_readable.js:113:10)

when i run this script:

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

var child = new (forever.Monitor)('./lstnr.js', {
    silent: true,
    'logFile': './main.log',
    'outFile': './out.log',
    'errFile': './err.log'
});

child.start();
setTimeout(function() {
    child.stop();
    setTimeout(function() {
        child.restart();
        // i try also child.start(); command, but result is same.
    }, 2000);
}, 1000);

Please fix it, if it's your bug.
Or how should I do starting child after stop it with log files options for correct working?
P.S. without log files options it works fine.
Thanks.

Can this daemonize the script?

In the readme there's this option:

'logFile': 'path/to/file', // Path to log output from forever process (when daemonized)

What does that mean? How is logFile used? I don't see a way to daemonize anything with forever-monitor.

logFile: '/dev/null' does not work

I want to discard all logs, stderr and stdout
Setting
logFile: '/dev/null'
does crash the script, but I suppose the "silent" option might already do what I want, can you confirm?

The .foreveignore file doesn't work

Hi guys,

The .foreveignore file doesn't work for me, so could you please take a look and fix it ?

After hours of research I found where's bug located.
In the watchFilter method (https://github.com/nodejitsu/forever-monitor/blob/master/lib/forever-monitor/plugins/watch.js) you must change the following code:

length = this.watchIgnorePatterns
to
length = this.watchIgnorePatterns.length;

and

testName = (this.watchIgnorePatterns[i].charAt(0) !== '/') ? relFileName : fileName;

to

if(typeof(this.watchIgnorePatterns[i]) !== "string") continue;
testName = (this.watchIgnorePatterns[i].charAt(0) !== '/') ? relFileName : fileName;

Thx

forever can't restart application after several times

I found forever sometimes don't restart application after many times.
Normally forever will print these words to log file:

error: Forever detected script exited with code: 8
error: Forever restarting script for 2 time

But after several times it suddenly occur error:

error: Forever detected script exited with code: 8

/usr/lib/node_modules/forever/node_modules/forever-monitor/node_modules/broadway/node_modules/eventemitter2/lib/eventemitter2.js:283
          throw arguments[1]; // Unhandled 'error' event
                         ^
Error: Cannot stop process that is not running.
    at /usr/lib/node_modules/forever/node_modules/forever-monitor/lib/forever-monitor/monitor.js:332:26
    at process._tickCallback (node.js:415:13)

And it will not start progress for application like usual . But the strange thing is log file will still append log information like the application still alive.
Is it a bug with forever or eventemitter2 ?

forever-monitor & init.d script

Hello, I have a problem with "forever-monitor" and a custom init.d script on Ubuntu 12.04. These are the steps:
init.d script --> nodejs script (forever-monitor) --> nodejs script (app-server.js)

This is working properly with "sudo service app-server start" and it also runs successfully on machine boot.

The problem is that when I do "sudo service app-server stop", only the process of "forever-monitor" stops. The "app-server" process is still running. I'm using the "killTree: true" option in forever-monitor configuration, but it seems that it's not working properly with my init.d script.

I could kill the remaining ("app-server") process myself (by PID), but I can't find a .pid file for that process in the pid file defined in configuration ("pidFile"). The "outFile" and "errFile" are being created successfully, so the paths in configuration are ok.

Is there any way to use "killTree" or to get the child process pid? I don't want to use "forever" from cli, because I like the js way with "forever-monitor".

child.unref()

The ChildProcess object is made available through the .child property of the forever object, however calling .child.unref() with the spawnWith: {detached: true} options passed along, it seems you're still unable to detach the parent process from the child.

For example:

var Daemon = require('forever-monitor').Monitor;

var deamon = new Daemon('daemon.js', {
    max: 1,
    silent: true,
    spawnWith: {
        detached: true
    }
    // ...
});

deamon.start();
deamon.child.unref();

process.exit();

I would expect the child process here to continue, but it's killed instantly along with the parent. What am I doing wrong?

Installing forever-monitor fails for node 0.6.10

[swright@swright-dev noschema]$ npm install forever-monitor
npm http GET https://registry.npmjs.org/forever-monitor
npm http 200 https://registry.npmjs.org/forever-monitor

npm ERR! Error: No compatible version found: forever-monitor
npm ERR! No valid targets found.
npm ERR! Perhaps not compatible with your version of node?
npm ERR! at installTargetsError (/usr/local/lib/node_modules/npm/lib/cache.js:488:10)
npm ERR! at next_ (/usr/local/lib/node_modules/npm/lib/cache.js:438:17)
npm ERR! at next (/usr/local/lib/node_modules/npm/lib/cache.js:415:44)
npm ERR! at /usr/local/lib/node_modules/npm/lib/cache.js:408:5
npm ERR! at saved (/usr/local/lib/node_modules/npm/lib/utils/npm-registry-client/get.js:147:7)
npm ERR! at Object.oncomplete (/usr/local/lib/node_modules/npm/node_modules/graceful-fs/graceful-fs.js:231:7)
npm ERR! You may report this log at:
npm ERR! http://github.com/isaacs/npm/issues
npm ERR! or email it to:
npm ERR! [email protected]
npm ERR!
npm ERR! System Linux 2.6.18-274.el5
npm ERR! command "node" "/usr/local/bin/npm" "install" "forever-monitor"
npm ERR! cwd /home/swright/code/noschema
npm ERR! node -v v0.6.10
npm ERR! npm -v 1.1.0-3
npm ERR! message No compatible version found: forever-monitor
npm ERR! message No valid targets found.
npm ERR! message Perhaps not compatible with your version of node?
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/swright/code/noschema/npm-debug.log
npm not ok

use args instead of options

Options is a too much generic word to define the command arguments. I propose to set args as an alias of it.

.stop() doesn't work for me

Hello!
I'm trying to build a CLI tool with forever-monitor.
I'm having trouble stopping a child process, for some reason it won't work!

It's probably me, but help would be nice :)

Main js file:

var path = require('path'),
    forever = require('forever-monitor'),
    script = path.join(__dirname, 'server.js');

var child1 = new (forever.Monitor)(script, {});
child1.start();

setTimeout(function() {
  child1.stop();
}, 500);

server.js

setInterval(function(){
  console.log('heartbeat');
}, 100);

Thanks!

Make it not node specific

forever-monitor should have an API similar to that of child_process.spawn, with events applicable for a process monitor (e.g. restart).

I eventually want this module to be as minimal as possible.

Issue when spawning process which uses cluster module on Windows

I'm spawn()ing a monitor.js file (similar to how forever does it) and in this monitor.js file, I'm instantiating forever-monitor like this:

var child = new (forever.Monitor)(mainServerScript, {
  max: maxRestarts,
  silent: true,
  args: args
});
// ...
child.start();

My mainServerScript script makes use of the cluster module and spawns processes using

cluster.fork()

For some reason, on Windows, this causes a new window to popup (for each cluster.fork) and disappear immediately after and it causes ALL my node processes to terminate without error.

Note that the issue doesn't happen when using forever CLI - Only my custom CLI using forever-monitor.

`Monitor.restart` sets `forceRestart`, but doesn't unset it on restart

Attempting to stop a script after it has been restarted at least once causes the script to become unstoppable until .start() is called again.

Line 306 of monitor.js shows that forceRestart is set to true before the child process is killed.

I see that line 175 of the same file has forceRestart being set to false, but I don't believe this is called (is it related?) unless .start() is called explicitly.

So essentially, after restarting a script, I cannot stop it anymore, as it starts right back up again.

Node environment test causes spawn failure when 'node' in script name

The environment test at the start of the Monitor.prototype.trySpawn function causes commands with node in the name to fail spawning. Changing the regex to include word and space boundaries seems to solve the issue:

Monitor.prototype.trySpawn = function () {
  if (/\bnode\s/.test(this.command) && this.checkFile && !this.childExists) {
    try {
      var stats = fs.statSync(this.args[0]);
      this.childExists = true;
    }
    catch (ex) {
      return false;
    }
  }

Make it not node specific

forever-monitor should have an API similar to that of child_process.spawn, with events applicable for a process monitor (e.g. restart).

I eventually want this module to be as minimal as possible.

Append logs instead of overwriting them?

Hello,

Every time that I need to stop the server.js script that runs forever monitor, the log files get overwritten. Is there a way to specify that I would like to append to this file instead of overwriting them?

I'm using the logFile, outFile, and errFile options to log.

Error: ELOOP, stat

I am using keystonejs (http://keystonejs.com/) and when running it via forever -w keystone.js every now and then (when reloading I think) for some odd reason I get:

/usr/local/lib/node_modules/forever/node_modules/forever-monitor/node_modules/watch/main.js:63
    if (err) throw err;
                   ^
Error: ELOOP, stat '/home/vagrant/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server/server'

Couldn't find anything online. Any idea what the issue could be?

Logger causes TypeError when options.stdio = [0, 1, 2]

If you set options.stdio = [0, 1, 2] then the logger plugin causes a TypeError.

test/node_modules/forever-monitor/lib/forever-monitor/plugins/logger.js:56
  monitor.child.stdout.on('data', function onStdout(data) {
                       ^
TypeError: Cannot call method 'on' of null
  at startLogs (test/node_modules/forever-monitor/lib/forever-monitor/plugins/logger.js:56:28)

forever.stop() kills all processes

Got a newbie question. I have code that starts and montors all forever processes. I can stop and or restart a given process from the CLI. But if I try to stop a process from code using the forever.stop(index). I get all the processes stopping.

Expected?

Thanks,
Stephan

forever-monitor crashes under Foreman

Under the foreman gem (used by Heroku) forever monitor instantly crashes.

Output of node application.js

12:12:22 leo@xcom angry-wizard master node application.js  
Listening on *:300

Output of foreman start (where Procfile contains only web: node application.js)

12:04:10 leo@xcom angry-wizard master foreman start
12:12:22 web.1  | started with pid 5815
12:12:22 web.1  | 
12:12:22 web.1  | _stream_readable.js:745
12:12:22 web.1  |     while (!paused && (null !== (c = stream.read())))
12:12:22 web.1  |                                             ^
12:12:22 web.1  | TypeError: Property 'read' of object #<Socket> is not a function
12:12:22 web.1  |     at Socket.<anonymous> (_stream_readable.js:745:45)
12:12:22 web.1  |     at Socket.EventEmitter.emit (events.js:92:17)
12:12:22 web.1  |     at emitDataEvents (_stream_readable.js:771:10)
12:12:22 web.1  |     at Socket.Readable.on (_stream_readable.js:692:5)
12:12:22 web.1  |     at Monitor.startLogs (/home/leo/development/projects/angry-wizard/node_modules/deployd/node_modules/forever-monitor/lib/forever-monitor/plugins/logger.js:56:28)
12:12:22 web.1  |     at Monitor.EventEmitter.emit (/home/leo/development/projects/angry-wizard/node_modules/deployd/node_modules/forever-monitor/node_modules/broadway/node_modules/eventemitter2/lib/eventemitter2.js:332:22)
12:12:22 web.1  |     at /home/leo/development/projects/angry-wizard/node_modules/deployd/node_modules/forever-monitor/lib/forever-monitor/monitor.js:152:10
12:12:22 web.1  |     at process._tickDomainCallback (node.js:459:13)
12:12:22 web.1  |     at Function.Module.runMain (module.js:499:11)
12:12:22 web.1  |     at startup (node.js:119:16)
12:12:22 web.1  | exited with code 8
12:12:22 system | sending SIGTERM to all processe

This is stopping me deploying an app using forever-monitor to Heroku. No idea why this is happening.

Can't kill child prozess

Managed to kill the parent process with forever.stop(hid); but can't stop the child.. any Ideas how to do ?
I've also tried using forever.kill(pid); and it works quite will until the parent process respawns his child process...

Using --debug as command or option doesn't work: [Error: Target script does not exist: --debug]

var child = forever.start(['node', '--debug', '_indexWithoutForever.js'], {
uid: 'production'
,silent: true
,logFile: '_logs/' + datetime + ' log.txt'
,outFile: '_logs/' + datetime + ' out.txt'
,errFile: '_logs/' + datetime + ' err.txt'
});
I expect to run: node --debug index.js
but instead of this it tries to load the --debug script: [Error: Target script does not exist: --debug]

Confused forever exit behaviour

I'm using -minUptime 5000 --spinSleepTime 500 as part of my forever start command. However, in the forever.log I see the process exit and restart "randomly" and I can't figure out how to just keep it running with no exit. There are no issue with the app itself, but since I run nodejs + nginx upstream, I periodically see 502 from nginx because forever exits.

What's are the right options so I stop the node process from exiting? Or, am I missing something fundamental?

-w and .foreverignore not working for subdirectories

I know that there are a few closed issues on this, and that patches (#50, #30, #13 ) have been made and merged. However, I still cannot make it work.

I want forever to ignore the log subdirectory

log/*.log

I have tried all the following in /path/to/app/.foreverignore:

log
log/*
*.log
*log*
**/log/**
**/*.log
**log**
/path/to/app/log/*.log

forever is started like this:

forever start -a -l /path/to/app/log/forever.log -o /path/to/app/log/out.log -e /path/to/app/log/err.log --watchDirectory /path/to/app -w --minUptime 1000 --spinSleepTime 1000 server.js

Am I doing anything wrong? And where is the documentation on .foreverignore format?

spawnWith.env seems to be ignored

[email protected]

$ node
> require('forever-monitor')
{ kill: [Function],
  checkProcess: [Function],
  Monitor: 
   { [Function]
     super_: { [Function] super_: [Function: EventEmitter] } },
  version: '1.1.0',
  start: [Function] }
> Monitor=require('forever-monitor').Monitor
{ [Function]
  super_: { [Function] super_: [Function: EventEmitter] } }
> child=new Monitor(['env'], {spawnWith:{env:{PORT:'123123'}}})
undefined
> child.on('stdout', function (d) {console.log(d+'')}); child.start();
undefined
> 
TERM_PROGRAM=iTerm.app
TERM=xterm-256color
SHELL=/bin/bash
USER=bradleymeck
COMMAND_MODE=unix2003
PATH=/opt/local/bin:/opt/local/sbin:/Applications/Cloud9.app/Contents/installs/c9local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/X11/bin:/usr/local/git/bin:/opt/local/bin
PWD=/Users/bradleymeck/Desktop/hiboo
DBUS_LAUNCHD_SESSION_BUS_SOCKET=/tmp/launch-3KzD2L/unix_domain_listener
LANG=en_US.UTF-8
ITERM_PROFILE=Default
SHLVL=1
HOME=/Users/bradleymeck
ITERM_SESSION_ID=w0t3p0
LOGNAME=bradleymeck
DISPLAY=/tmp/launch-9gNby2/org.macosforge.xquartz:0
_=/usr/local/bin/node

README could have an example on how to get the "typical" forever output

Could the README file show sample code to replicate the forever CLI debug prints?

I was expecting to get the debug output by default, but I had to dive into the source to realise it was the forever module doing that part:

monitor = new forever.Monitor('app.coffee', options)

monitor.on 'watch:restart', (info) ->
    console.error "restaring script because #{info.file} changed"

monitor.on 'restart', ->
    console.error "Forever restarting script for #{monitor.times} time"

monitor.on 'exit:code', (code) ->
    console.error "Forever detected script exited with code #{code}"

Take a signal or command while running a process to manually restart it.

Hi.

I've recently replaced nodemon with forever because nodemon's watch functionality has issues (it watches the node_modules dir even if you configure it correctly).

One of the great features of nodemon (for me) is the ability to type "rs" to manually restart the process. This is nice because it allows me to restart the server but skip re-initializing the whole grunt/gulp setup.

Is this possible to implement with Forever?

toString silliness

> var f = require("forever-monitor")
undefined
> f
{ kill: [Function],
  checkProcess: [Function],
  Monitor: 
   { [Function]
     super_: { [Function] super_: [Function: EventEmitter] } },
  version: '1.0.2',
  start: [Function] }
> f.Monitor
{ [Function]
  super_: { [Function] super_: [Function: EventEmitter] } }
> var m = new f.Monitor("app.js")
undefined
> m
undefined
> typeof m
'object'
> JSON.stringify(m)
'{"silent":false,"killTree":true,"uid":"akFd","childExists":false,"checkFile":true,"times":0,"minUptime":0,"spinSleepTime":null,"command":"/usr/local/n/versions/0.8.3/bin/node","args":["app.js"],"spawnWith":{},"fork":false,"cwd":null,"hideEnv":[],"_env":{},"_hideEnv":{},"watchIgnoreDotFiles":true,"watchIgnorePatterns":[],"delimiter":"::","_events":{},"wildcard":true,"listenerTree":{"start":{},"restart":{},"exit":{}},"options":{"bootstrapper":{}},"env":"development","plugins":{},"initialized":false,"bootstrapper":{},"initializers":{},"initlist":[]}'

Seems like at some point, toString is replaced with something that always returns "undefined" (as a string). This on its own isn't a showstopper, but it does hint at the possibility of something very very strange happening with this object.

Fails with "Error: spawn ENOENT" when node.js is installed under a path that contains spaces

Running the example:

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

  var child = new (forever.Monitor)('testscript.js', { // yes i created this file
    max: 3,
    silent: true,
    options: []
  });

  child.on('exit', function () {
    console.log('your-filename.js has exited after 3 restarts');
  });
 child.on('error', function(e) {
     console.log("wtf: ",e)
 })

  child.start();
node foreverMonitorTest.js

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)

I'm on windows 8 64 bit, node v0.10.29 .

My node.js installation is at "C:\Program Files\nodejs\node.exe". Line 246 of monitor.js (return spawn(command, args, this.spawnWith);) has the command "C:\Program".

Splitting the command by spaces renders an invalid/broken command

This fails, at least on my windows machine:

var forever = require('forever-monitor');
var child = forever.start('server.js');

the result was:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:980:11)
    at Process.ChildProcess._handle.onexit (child_process.js:771:34)

Debugging the problem yielded the following (excerpt from monitor.js - trySpawn()):

Monitor.prototype.trySpawn = function () {
  var command, cmdarr, stats, args;

  if (/[^\w]node$/.test(this.command) && this.checkFile && !this.childExists) {
    try {
      stats = fs.statSync(this.args[0]);
      this.childExists = true;
    }
    catch (ex) {
      return false;
    }
  }

  this.spawnWith.cwd = this.cwd || this.spawnWith.cwd;
  this.spawnWith.env = this._getEnv();

  if (this.stdio) {
    this.spawnWith.stdio = this.stdio;
  }

_at this point, command === "C:\Program Files\nodejs\node.exe"_

  cmdarr  = this.command.trim().split(/\s+/);
  command = this.command; 

_now its "C:\Program"_

  args    = this.args;

  if (cmdarr.length > 1) {
    command = cmdarr[0];
    args = cmdarr.slice(1).concat(this.args);
  }

  if (this.fork) {
    if (!this.stdio) {
      this.spawnWith.stdio = [ 'pipe', 'pipe', 'pipe', 'ipc' ];
    }
    return spawn(command, args, this.spawnWith);
  }

  return spawn(command, args, this.spawnWith);
};

I'm not entirely sure if it is something that needs fixing (would love a comment on that).

In the meanwhile my workaround was to start with the "command" option:

var forever = require('forever-monitor');
var child = forever.start('server.js', { command: 'node' });

Relying on the fact that node is in my environment path

Getting forever-monitor to behave like forever in Windows

I can't figure out how to get forever-monitor to run in the background on Windows.
If I install forever and run using the CLI, it works fine, but I cannot replicate this behavior using my own custom monitor built on top of forever-monitor.

I was looking through forever's source code to try to figure out how it's done, but I couldn't find the lines responsible for this. What am I missing? Is there a general pattern I should follow to get this working?

Right now, I'm spawning a monitor.js process using spawn() and setting the 'detached' property to true (like forever does).

Inside monitor.js, I require('forever-monitor') and I create a new (forever.Monitor)(...) object, and call start() on it...

child.restart() returns error

I would like to have the ability to call child.restart() manually without error.
Is there any way to do it ?
May you guide me to implement it ?


I have to say, I'm comming to this request since grunt-forever doesn't work properly for restarting tasks.

flag to disable logging altogether

Hi, thanks for your great tool first of all.

I have a suggestion tho: don't you think it would be nice to have a flag to disable logging?

In my app I use winston already, and see no need to have another layer of logging.

Hope to hear from you :)

forever stop

/home/danhuang/forever-master/lib/node_modules/nssocket.js:33
socket = common.createSocket(options);
^
TypeError: Object # has no method 'createSocket'
at new exports.NsSocket (/home/danhuang/forever-master/lib/node_modules/nssocket.js:33:21)
at getProcess (/home/danhuang/forever-master/lib/forever.js:97:18)
at _asyncMap (/home/danhuang/forever-master/lib/node_modules/async.js:178:13)
at async.forEach (/home/danhuang/forever-master/lib/node_modules/async.js:79:13)
at Array.forEach (native)
at _forEach (/home/danhuang/forever-master/lib/node_modules/async.js:19:24)
at async.forEach (/home/danhuang/forever-master/lib/node_modules/async.js:78:9)
at _asyncMap (/home/danhuang/forever-master/lib/node_modules/async.js:177:9)
at Object.doParallel as map
at /home/danhuang/forever-master/lib/forever.js:130:11

[PATCH] Processes aren't killed on Windows

If watch is set to true processes should be killed/restarted every time a change is made, but this won't happen actually.

The problem is in common.js, in export.kill.
Currently the code spawns a kill -9 command, which doesn't exist in Windows.
Instead something like this will work:

  -spawn('kill', ['-9'].concat(pids)).on('exit', callback || function() {});

  +pids.forEach(function(pid){
  +  process.kill(pid);
  +  (callback || function() {})();
  +});

forever myapp.js results in exception if node.exe is in a path containing spaces.

Platform: win7-x64
Node: C:\Program Files\nodejs\node.exe

If I use forever I get an exception:

events.js:72
throw er; // Unhandled 'error' event
^
Error: spawn ENOENT
at errnoException (child_process.js:975:11)
at Process._handle.onexit (child_process.js:766:34)

Reason: the variable command is "C:\Program" in monitor.js (line 225):

cmdarr = this.command.trim().split(/\s+/);
command = this.command;
args = this.args;

if (cmdarr.length > 1) {
command = cmdarr[0];
args = cmdarr.slice(1).concat(this.args);
}

if (this.fork) {
if (!this.stdio) {
this.spawnWith.stdio = [ 'pipe', 'pipe', 'pipe', 'ipc' ];
}
return spawn(command, args, this.spawnWith);
}

return spawn(command, args, this.spawnWith);

cron-like execution

Add a config option to exec a command at some defined hours as cron does.

Global Leak in ps-tree

The ps-tree module included with the installation of forever-monitor has a global leak of the child variable.

The ps-tree package.json directs to the following repo https://github.com/dominictarr/ps-tree which no longer exists.

Fix is easy to declare the child variable in the function scope, thought you might want to consider forking the ps-tree module and maintain it with forever

Cheers,

Jay

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.