Asked  7 Months ago    Answers:  5   Viewed   31 times

Since this post has gotten a lot of attention over the years, I've listed the top solutions per platform at the bottom of this post.


Original post:

I want my node.js server to run in the background, i.e.: when I close my terminal I want my server to keep running. I've googled this and came up with this tutorial, however it doesn't work as intended. So instead of using that daemon script, I thought I just used the output redirection (the 2>&1 >> file part), but this too does not exit - I get a blank line in my terminal, like it's waiting for output/errors.

I've also tried to put the process in the background, but as soon as I close my terminal the process is killed as well.

So how can I leave it running when I shut down my local computer?


Top solutions:

  • Systemd (Linux)
  • Launchd (Mac)
  • node-windows (Windows)
  • PM2 (Node.js)

 Answers

72

Copying my own answer from How do I run a Node.js application as its own process?

2015 answer: nearly every Linux distro comes with systemd, which means forever, monit, PM2, etc are no longer necessary - your OS already handles these tasks.

Make a myapp.service file (replacing 'myapp' with your app's name, obviously):

[Unit]
Description=My app

[Service]
ExecStart=/var/www/myapp/app.js
Restart=always
User=nobody
# Note Debian/Ubuntu uses 'nogroup', RHEL/Fedora uses 'nobody'
Group=nogroup
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/myapp

[Install]
WantedBy=multi-user.target

Note if you're new to Unix: /var/www/myapp/app.js should have #!/usr/bin/env node on the very first line and have the executable mode turned on chmod +x myapp.js.

Copy your service file into the /etc/systemd/system.

Start it with systemctl start myapp.

Enable it to run on boot with systemctl enable myapp.

See logs with journalctl -u myapp

This is taken from How we deploy node apps on Linux, 2018 edition, which also includes commands to generate an AWS/DigitalOcean/Azure CloudConfig to build Linux/node servers (including the .service file).

Tuesday, June 1, 2021
 
subroutines
answered 7 Months ago
24

I did some research on this and I would do it like this.

Setup

beanstalkd

  1. Install beanstalkd. Another message queue, BUT this one supports DELAYED PUTS. If you compile from source it is going to be a little harder because it depends on libevent(like memcached). But then again, I don't think you have to compile it from source, because there are a lot of binary packages available. For example on Ubuntu you can install beanstalkd by issuing the command:

    sudo apt-get install beanstalkd

node-beanstalk-client

  1. Install a beanstalkd client library. The best one I found was node-beanstalk-client. Because on the beanstalkd client library list this library isn't/wasn't mentioned(Then again I can add entries to the list, so I will add this one). The reasons I prefer this library over the others are:

    1. Npm package: I liked to use a npm package to install client library. The others did not have any.
    2. Active development: I prefer libraries which have later/more commits.

So to install it, after you have installed npm(the write way) you would just issue the following command:

npm install beanstalk_client

Code

consumer.js

var client = require('beanstalk_client').Client;

client.connect('127.0.0.1:11300', function(err, conn) {
    var reserve = function() {
        conn.reserve(function(err, job_id, job_json) {
            console.log('got job: ' + job_id);
            console.log('got job data: ' + job_json);
            console.log('module name is ' + JSON.parse(job_json).data.name);
            conn.destroy(job_id, function(err) {
                console.log('destroyed job');
                reserve();
            });
        });
    }

    reserve();
});

First start the consumer:

node consumer.js 

Next start producer.js. Five seconds(delay I specified) after you execute producer.js, consumer.js will process the message.

producer.js

var client = require('beanstalk_client').Client;
client.connect('127.0.0.1:11300', function(err, conn) {
    var job_data = {"data": {"name": "node-beanstalk-client"}};
    var priority = 0;
    var delay = 5;
    var timeToRun = 1;
    conn.put(priority, delay, timeToRun, JSON.stringify(job_data), function(err, job_id) {
        console.log('put job: ' + job_id);
        process.exit();
    });
});

to start just issue:

node producer.js
Saturday, July 10, 2021
 
Gersom
answered 5 Months ago
39

Yes, built-in/core modules process does this:

So, just say var process = require('process'); Then

To get PID (Process ID):

if (process.pid) {
  console.log('This process is your pid ' + process.pid);
}

To get Platform information:

console.log('This platform is ' + process.platform);

Note: You can only get to know the PID of child process or parent process.


Updated as per your requirements. (Tested On WINDOWS)
var exec = require('child_process').exec;
var yourPID = '1444';

exec('tasklist', function(err, stdout, stderr) { 
    var lines = stdout.toString().split('n');
    var results = new Array();
    lines.forEach(function(line) {
        var parts = line.split('=');
        parts.forEach(function(items){
        if(items.toString().indexOf(yourPID) > -1){
        console.log(items.toString().substring(0, items.toString().indexOf(yourPID)));
         }
        }) 
    });
});

On Linux you can try something like:

var spawn = require('child_process').spawn,
    cmdd = spawn('your_command'); //something like: 'man ps'

cmdd.stdout.on('data', function (data) {
  console.log('' + data);
});
cmdd.stderr.setEncoding('utf8');
cmdd.stderr.on('data', function (data) {
  if (/^execvp()/.test(data)) {
    console.log('Failed to start child process.');
  }
});
Wednesday, July 28, 2021
 
wavyGravy
answered 4 Months ago
26

try this from a DOS/CMD shell:

powershell.exe -windowstyle hidden -file C:iis_test.ps1
Monday, August 9, 2021
 
Ahmed Haque
answered 4 Months ago
88

Check out srvany.exe from the Resource Kit. This will let run anything as a service.

You can pass parameters in the service definition to your executable via srvany.exe so you could run a batch file as a service by seting the registry as follows:

[HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesMyServiceParameters]
"Application"="C:\Windows\System32\cmd.exe"
"AppParameters"="/C C:\My\Batch\Script.cmd"
"AppDirectory"="C:\My\Batch"

Note: if you set up these keys in RegEdit rather than using a file you only need single backslashes in the values.

Thursday, September 30, 2021
 
Kumar V
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share