通过从NodeJS中执行PHP脚本来重新启动NodeJS

I have a problem trying to update a folder and deploy its contents again. I have to use NodeJS and have gotten port 8080 to work with. I have tried to create a php script (update.php):

<?php
echo exec("git pull");
echo exec("node app.js");
?>

Now i want to start the NodeJS script to update and the ultimate goal is to be able to restart the server.

I use the express module:

app.get('/Update', function(req,res) {
   exec("php update.php", function(error, stdout, stderr) {
      process.exit(0);
   }
}

The problem is that the NodeJS server quits when it gets a response from the script but the script tries to start the NodeJS server. This obviously cannot happen since it is already running on the specified port.

Now i found on google to use the module called 'nodemon' however I am not given sudo access so installing this is out of the question. Other results are using

ps aux | grep node
kill -9 PROCESS_ID

This also yields problems since it is hard to configure the PHP script to kill the specified process but aside from that there are other NodeJS servers running in other child folders of the parent folder I am given. This means that if I'd use 'killall node' I'd get a lot of people angry that I killed their servers.

What is the best approach to solving this problem using only port 8080 and wanting to deploy the changes in the Github repo when accessing a certain link?

You can get the node's process id by Node.js command process.pid.

You can then make a bash script that executes all your commands and give the PID in environment variable.

1) Forget the update.php

2) route

app.get('/update', function(req, res) {
  var spawn = require('child_process').spawn;
  spawn('sh', [ 'update.sh' ], {
    env: { NODE_PID: process.pid }
  });
});

3) update.sh

git pull
kill -9 $NODE_PID
node app.js

There are a couple of different approaches you could use. I would suggest using a Job Queue so that you never have to restart the process. Using something like Faye your express app could send update messages to the Faye server...

app.get('/update', function (req, res) {

  // connect to local service on 8000
  var client = new faye.Client('http://localhost:8000/');

  client.publish('/update', {
    message: 'pull'
  });

  res.sendStatus(200);
});

Your server would accept requests as follows...

var server = http.createServer(),
bayeux = new faye.NodeAdapter({mount: '/'});

bayeux.attach(server);

server.listen(8000);

And your subscriber application could listen to the /update queue for pull requests. If you run this using forever or pm2 your problem is solved.

Subscriber...

var client = new faye.Client('http://localhost:8000/');

client.subscribe('/update', function (message) {
  exec("cd /your/working/dir && git pull origin master", function(error, stdout, stderr) {
    process.exit(0);
  }  
});

Or as another reader suggested you could and probably should use git hooks. A nice way to deploy is to have a bare repo.