Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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?

like image 498
Jerome WAGNER Avatar asked Feb 04 '11 22:02

Jerome WAGNER


People also ask

How do I start a node server in the background?

Method 3: Another method which can be used to run a node. js app as a background by using nohup. The nohup is another Command Line Interface Tool which can be used to run a node. js app as a background service.


2 Answers

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(); 
like image 174
Baggz Avatar answered Sep 21 '22 00:09

Baggz


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.

like image 23
Budleigh Avatar answered Sep 21 '22 00:09

Budleigh