How does one start a node.js server as a daemon process?


Question

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?

Thanks for your help

1
76
2/8/2011 4:37:26 AM

Accepted Answer

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();
87
6/29/2017 8:03:41 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon