How does one start a node.js server as a daemon process?
In Python Twisted, you have the twistd
command that helps you with a number of things related to running your application (daemonize it for example).
How do you daemonize a node.js server so that it can run even after the current session is closed?
Forever is answer to your question.
Install
$ curl https://npmjs.org/install.sh | sh
$ npm install forever
# Or to install as a terminal command everywhere:
$ npm install -g forever
Usage
Using Forever from the command line
$ forever start server.js
Using an instance of Forever from Node.js
var forever = require('forever');
var child = new forever.Forever('your-filename.js', {
max: 3,
silent: true,
args: []
});
child.on('exit', this.callback);
child.start();
If you need your process to daemonize itself, not relaying on forever - you can use the daemonize module.
$ npm install daemonize2
Then just write your server file as in example:
var daemon = require("daemonize2").setup({
main: "app.js",
name: "sampleapp",
pidfile: "sampleapp.pid"
});
switch (process.argv[2]) {
case "start":
daemon.start();
break;
case "stop":
daemon.stop();
break;
default:
console.log("Usage: [start|stop]");
}
Mind you, that's rather a low level approach.