Code Monkey home page Code Monkey logo

daemon.node's Introduction

daemon

Build Status

Turn a node script into a daemon.

install via npm

npm install daemon

Requires node >= 0.8

examples

// this code is run twice
// see implementation notes below
console.log(process.pid);

// after this point, we are a daemon
require('daemon')();

// different pid because we are now forked
// original parent has exited
console.log(process.pid);

api

daemon(opt)

Respawn the process (self) as a daemon. The parent process will exit at the point of this call. opt parameter see below.

daemon.daemon(script, args, opt)

Spawn the script with given args array as a daemonized process. Return the child process object.

opt can optionally contain the following arguments:

  • stdout (file descriptor for stdout of the daemon)
  • stderr (file descriptor for stderr of the daemon)
  • env (environment for the daemon) (default: process.env)
  • cwd (current working directory for daemonized script) (default: process.cwd)

implementation notes

Daemon actually re-spawns the current application and runs it again. The only difference between the original and the fork is that the original will not execute past the daemon() call whereas the fork will.

node versions prior to 0.8

Using this module on older versions of node (or older versions of this module) are not recommended due to how node works internally and the issues it can cause for daemons.

Contributors

Charlie Robbins
Pedro Teixeira
James Halliday
Zak Taylor
Daniel Bartlett
Charlie McConnell
Slashed
Roman Shtylman

daemon.node's People

Contributors

avianflu avatar bmeck avatar defunctzombie avatar egoldblum avatar indexzero avatar jfhbrook avatar kpdecker avatar pdehaan avatar slashed avatar tomyan 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

daemon.node's Issues

In server daemon, fs.asyncFun only works after killing 1st request

var daemon = require('daemon');
var fs = require('fs');
var http = require('http');

http.createServer(function(req, res) {
  fs.readFile('yourFile', 'utf8', function(err, data) {
    res.end(data);
  });    
}).listen(8080);

daemon.daemonize('app.log', 'app.pid', console.log);

The above server freezes at the 1st http request, fs.readFile never triggers the callback.
It's only after killing the 1st request in the browser that everything works.

Cannot find module '../build/default/daemon'

I runned into this issue using forever on EC2.

I my case it looks like the build differs from standard?

binding = require('../build/default/daemon'),

should be :

binding = require('../build/Release/daemon'),

in lib/daemon.js

nvm and daemon.node

[ext6trac@ace1 bin]$ nvm ls
N/A
current:
[ext6trac@ace1 bin]$ nvm install 0.8.16

################################################################## 100,0%

Now using node v0.8.16
[ext6trac@ace1 bin]$ nvm ls
v0.8.16
current: v0.8.16
[ext6trac@ace1 bin]$ npm install daemon
npm http GET https://registry.npmjs.org/daemon
npm http 304 https://registry.npmjs.org/daemon

[email protected] preinstall /home/ext6trac/.nvm/bin/node_modules/daemon
bash ./install

Checking for program g++ or c++ : /usr/bin/g++
Checking for program cpp : /usr/bin/cpp
Checking for program ar : /usr/bin/ar
Checking for program ranlib : /usr/bin/ranlib
Checking for g++ : ok
Checking for node path : not found
Checking for node prefix : ok /home/ext6trac/.nvm/v0.8.16
'configure' finished successfully (0.034s)
Waf: Entering directory /home/ext6trac/.nvm/bin/node_modules/daemon/build' [1/2] cxx: src/daemon.cc -> build/Release/src/daemon_1.o [2/2] cxx_link: build/Release/src/daemon_1.o -> build/Release/daemon.node Waf: Leaving directory/home/ext6trac/.nvm/bin/node_modules/daemon/build'
Build failed: -> task failed (err #-1):
{task: cxx_link daemon_1.o -> daemon.node}
[email protected] node_modules/daemon
[ext6trac@ace1 bin]$

Daemon fork doesn't inherit Node CLI flags such as --enable_gc

I discovered that if my node script was launched with any Node CLI flags such as --enable_gc (which exposes the internal Node Garbage Collector), this flag does not pass down to the daemon fork. Example:

node --enable_gc mydaemon.js

I see that internal node flags are not included on the process.argv array, so there is apparently no way the daemon module can preserve them.

I worked around this by detecting the presence of global.gc and then splicing the --enable_gc flag back into the process.argv array just before calling daemon:

if (!process.env.__daemon && global.gc) {
    process.argv.splice( 1, 0, '--expose_gc' );
}
require('daemon')();

- Joe

node throws ev_rt_now error on Ubuntu & node-0.5.0pre

Reported by: @nakedslavin

enviroment:
node --v: 0.5.0 pre
npm -v: 1.12
python -v: 2.6.6
daemon 0.30 or something

NPM install (-g) goes fine, however it throws the following exception:

ubuntu:~$ forever

node.js:183
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: /usr/local/lib/node_modules/forever/node_modules/daemon/build/default/daemon.node: undefined symbol: ev_rt_now
at Object..node (module.js:472:11)
at Module.load (module.js:339:31)
at Function._load (module.js:298:12)
at require (module.js:367:19)
at Object. (/usr/local/lib/node_modules/forever/node_modules/daemon/lib/daemon.js:10:15)
at Module._compile (module.js:427:26)
at Object..js (module.js:466:10)
at Module.load (module.js:339:31)
at Function._load (module.js:298:12)
at require (module.js:367:19)

for some reason this problem persists only on my ubuntu machine, os x works just fine..

Separate log files for stdout and stderr

I need stdout and stderr in separate log files. Would send pull request if I knew C.

Current signature:

require("daemon").daemonize(logPath, pidFile, ...

Proposed optional new signature:

require("daemon").daemonize({
    stdout: stdoutLogPath,
    stderr: stderrLogPath
}, pidFile, ...

Thanks!

process.on('exit', cb) does not fire from child

It appears that process-related signal events do not fire from the child process when using the daemon() function.

// Daemonize and write PID file
require('daemon')();
fs.writeFileSync('me.pid', process.pid);

process.on('exit', function() {
    // this callback will not fire
    fs.unlinkSync('me.pid');
});

// Stick around so we can kill(1) the child
setTimeout(function(){}, 60000);

setup travis-ci

The repo admin needs to log into travis-ci and enable it for this repo.

console.log no longer working

We just upgraded to node v0.6.17 and daemon v0.5.0 and are no longer getting log output. Here's an example script that results in an empty log:

var daemon = require('daemon'),
    fs = require('fs');

setTimeout( function() {
  console.log('Hello, log!');
}, 5000);

fs.open('daemon_test.log', 'w+', function (err, fd) {
  daemon.start(fd);
  daemon.lock('/tmp/daemon_test.pid');
});

http.get no longer works after daemon.start()

I have been using the node v0.4.X branch in production along with daemon.node. I recently tried to upgrade to v0.6.10 and noticed that my application would run but didn't appear to be doing anything. After digging in, I narrowed it down to http.get() specifically. After get() was called none of the callbacks are ever called. I reduced it down to a pretty straight forward example:

var daemon = require('daemon'); 
var fs  =  require('fs'); 
var http = require('http'); 
fs.open('test.log', 'w+', function (err, fd) { 
    daemon.start(fd); 
    var options = { 
       host: 'www.google.com', 
       port: 80, 
       path: '/index.html' 
    }; 
    console.log('Making request'); 
    http.get(options, function(res) { 
        console.log('Got response: ' + res.statusCode); 
    }).on('error', function(e) { 
        console.log('Got error: ' + e.message); 
    }); 
}); 

When this code is run, "Making request" is written to test.log, but
neither the callback or the error event are ever called. The
application will continue to run forever though and has to be killed
manually.

I am testing on CentOS 5.3

Error during installation on OSX Mountain Lion (10.8.1)

npm http GET https://registry.npmjs.org/daemon
npm http 200 https://registry.npmjs.org/daemon
npm http GET https://registry.npmjs.org/daemon/-/daemon-0.5.1.tgz
npm http 200 https://registry.npmjs.org/daemon/-/daemon-0.5.1.tgz

> [email protected] preinstall /Users/christian/git/wun/node_modules/daemon
> bash ./install

Traceback (most recent call last):
  File "/opt/local/bin/node-waf", line 16, in <module>
    Scripting.prepare(t, os.getcwd(), VERSION, wafdir)
  File "/opt/local/bin/../lib/node/wafadmin/Scripting.py", line 145, in prepare
    prepare_impl(t, cwd, ver, wafdir)
  File "/opt/local/bin/../lib/node/wafadmin/Scripting.py", line 135, in prepare_impl
    main()
  File "/opt/local/bin/../lib/node/wafadmin/Scripting.py", line 188, in main
    fun(ctx)
  File "/opt/local/bin/../lib/node/wafadmin/Scripting.py", line 241, in configure
    conf.sub_config([''])
  File "/opt/local/bin/../lib/node/wafadmin/Configure.py", line 221, in sub_config
    self.recurse(k, name='configure')
  File "/opt/local/bin/../lib/node/wafadmin/Utils.py", line 634, in recurse
    f(self)
  File "/Users/christian/git/wun/node_modules/daemon/wscript", line 13, in configure
    conf.check_tool("compiler_cxx")
  File "/opt/local/bin/../lib/node/wafadmin/Configure.py", line 181, in check_tool
    lst = os.listdir(d)
OSError: [Errno 2] No such file or directory: '/opt/local/bin/../lib/node/wafadmin/Tools'
[email protected] node_modules/daemon

Let me know if you need some more info.

binding sockets by hostnames fails

Here is me repo with bug description.

To be short: you can't listen to sockets at localhost, but can at 127.0.0.1.

Checked at OSX 10.7.3 and Debian with node-0.6.12 and latest daemon from npm.

Clarification on daemon management once daemon running?

Hi,

I'm a new to *nix daemons and node.js. From the readme examples, it's not clear how the daemon management occurs once the daemon is started (running script forked and parent process exited). For example:

  • how to stop the daemon?
  • how to restart daemon?
  • manual restart/start daemon as in the example each time it needs a restart or start up on boot (although yes, it could be added to a startup script or something)?

Best practices for the above questions for use of this daemon node module.

not possible to build on squeeze

On a Fresh Squeeze System (with node 0.6.1) it is not possible to build daemon.

The last Lines of the npm-debug.log are attached, if you need the complete file, just let me know!

174 verbose caching /usr/lib/node_modules/daemon/package.json                                                                                                
175 verbose loadDefaults [email protected]                                                                                                                        
176 info preinstall [email protected]                                                                                                                             
177 verbose unsafe-perm in lifecycle false                                                                                                                   
178 verbose Setting uid from 0 nobody                                                                                                                        
179 verbose stack at uid setting Error                                                                                                                       
180 verbose stack at uid setting     at exec (/usr/lib/node_modules/npm/lib/utils/exec.js:35:17)                                                             
181 verbose stack at uid setting     at Array.0 (/usr/lib/node_modules/npm/lib/utils/lifecycle.js:127:5)                                                     
182 verbose stack at uid setting     at EventEmitter._tickCallback (node.js:192:40)                                                                          
183 silly exec sh "-c" "node-waf configure build"                                                                                                            
184 silly spawning [ 'sh',                                                                                                                                   
185 silly spawning   [ '-c', 'node-waf configure build' ],                                                                                                   
186 silly spawning   '/usr/lib/node_modules/daemon' ]                                                                                                        
187 info [email protected] Failed to exec preinstall script                                                                                                       
188 ERR! error installing [email protected] Error: [email protected] preinstall: `node-waf configure build`                                                            
189 ERR! error installing [email protected] `sh "-c" "node-waf configure build"` failed with 1                                                                    
190 ERR! error installing [email protected]     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/lib/utils/exec.js:49:20)                                   
191 ERR! error installing [email protected]     at ChildProcess.emit (events.js:70:17)                                                                            
192 ERR! error installing [email protected]     at maybeExit (child_process.js:359:16)                                                                            
193 ERR! error installing [email protected]     at Process.onexit (child_process.js:395:5)                                                                        
194 info unbuild /usr/lib/node_modules/daemon                                                                                                                
195 verbose from cache /usr/lib/node_modules/daemon/package.json                                                                                             
196 info preuninstall [email protected]                                                                                                                           
197 info uninstall [email protected]                                                                                                                              
198 verbose unbuild [email protected] [ true, '/usr/lib/node_modules', '/usr/lib/node_modules' ]                                                                  
199 info postuninstall [email protected]                                                                                                                          
200 verbose installOne cb [email protected]                                                                                                                       
201 ERR! [email protected] preinstall: `node-waf configure build`                                                                                                 
202 ERR! `sh "-c" "node-waf configure build"` failed with 1                                                                                                  
203 ERR!                                                                                                                                                     
204 ERR! Failed at the [email protected] preinstall script.                                                                                                       
205 ERR! This is most likely a problem with the daemon package,                                                                                              
206 ERR! not with npm itself.                                                                                                                                
207 ERR! Tell the author that this fails on your system:                                                                                                     
208 ERR!     node-waf configure build                                                                                                                        
209 ERR! You can get their info via:                                                                                                                         
210 ERR!     npm owner ls daemon                                                                                                                             
211 ERR! There is likely additional logging output above.                                                                                                    
212 ERR!                                                                                                                                                     
213 ERR! System Linux 2.6.32-5-amd64                                                                                                                         
214 ERR! command "node" "/usr/bin/npm" "install" "daemon" "-g"                                                                                               
215 ERR! cwd /root                                                                                                                                           
216 ERR! node -v v0.6.1                                                                                                                                      
217 ERR! npm -v 1.0.105                                                                                                                                      
218 ERR! code ELIFECYCLE                                                                                                                                     
219 verbose exit [ 1, true ] 

TypeError: "cwd" must be a string on Node 8

After upgrading to Node 8, we have an error on startup when launching a NodeBB server.
This issue has been documented here : https://community.nodebb.org/topic/10765/error-starting-nodebb-after-upgrade

And here is the full error stack which has its origin in the daemon module used by NodeBB :

TypeError: "cwd" must be a string
    at normalizeSpawnArguments (child_process.js:380:11)
    at Object.exports.spawn (child_process.js:465:38)
    at Function.module.exports.daemon (/www/node-bb/node_modules/daemon/index.js:50:31)
    at module.exports (/www/node-bb/node_modules/daemon/index.js:25:20)
    at /www/node-bb/loader.js:223:21
    at FSReqWrap.oncomplete (fs.js:135:15)

According to the API documentation, process.cwd() is effectively a method : https://nodejs.org/api/process.html#process_process_cwd

The fix is quite trivial and i will provide a Pull Request for it.

Unable to load shared library /Users/gabriel/app/node_modules/forever/node_modules/daemon/lib/daemon.v0.6.11.node

Hi,

I am using Node v0.6.11 on Mac OSX Lion.

I did npm rebuild and daemon.v0.6.11.node was rebuilt. (before it was daemon.v0.6.10.node).

When running forever module (that loads daemon module) I get:

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: Unable to load shared library /Users/gabriel/Work/jillix/node_modules/forever/node_modules/daemon/lib/daemon.v0.6.11.node
    at Object..node (module.js:472:11)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Module.require (module.js:354:17)
    at require (module.js:370:17)
    at Object.<anonymous> (/Users/gabriel/app/node_modules/forever/node_modules/daemon/lib/daemon.js:12:11)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)

otool says:

gabriel$ otool -L node_modules/forever/node_modules/daemon/lib/daemon.v0.6.11.node 
node_modules/forever/node_modules/daemon/lib/daemon.v0.6.11.node:
    /usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 52.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 159.1.0)

OS X: (libev) kevent: Bad file descriptor

Hi, Charlie. What is the status of forking on OS X?

I am daemonizing in the first tick; but subsequent i/o is failing.

I am not certain, but I believe I am getting this error the first time I do i/o on a file (Unix socket); but not the first time I do i/o at all (I opened the socket).

I saw that you have discussed this in related projects; and I imagine you are using daemon.node in your own work. So how have you gotten it working on OS X?

Thanks!

does not work with cluster

cluster.isMaster is true for all child processes spawned under a daemon that was created with this module. This can cause an infinite tree of processes to form if the app is forking under the conditional cluster.isMaster and can potentially bring down a whole system. The only way of stopping it is a reboot.

Object #<Object> has no method 'daemonize'

TypeError: Object # has no method 'daemonize'

Code:

var
config = require('./config').Config,
daemon = require('daemon');

daemon.daemonize({ stdout:config.accessLog, stderr:config.errorLog }, config.pid, function (err, pid) {
if (err) {
return console.error('Error starting daemon: ' + err);
}
console.log('Daemon started successfully with pid: ' + pid);
});

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.