How to run a Node.js app as a background service?

Sometimes, we want to run a Node.js app as a background service.

In this article, we’ll look at how to run a Node.js app as a background service.

How to run a Node.js app as a background service?

To run a Node.js app as a background service, we can use the daemon module.

To install it, we run

npm i daemon

Then we use it by writing

const daemon = require('daemon');

daemon.daemonize({
  stdout: './log.log',
  stderr: './log.error.log'
}, './node.pid', (err, pid) => {
  if (err) {
    console.log(err);
    return process.exit(-1);
  }
  console.log(pid);
});

to call daemon.daemonize with an object with the path for stdout and stderr set to the log file path as the 1st argument.

The 2nd argument is the path to the script we want to run.

The 3rd argument is the callback that runs when daemon.daemonize is done.

If there’s an error, err will be set.

pid is the process ID and it’ll be set when the daemon is started.

Conclusion

To run a Node.js app as a background service, we can use the daemon module.