Executing nodejs script file in PHP using exec()

  1. check whether the modules are installed (npm install)
  2. run the execin the node application current working directory:
exec("cd ". dirname($nodeJsPath). " && node nodefunc.js 2>&1", $out, $err);

Your goal is to execute a node command after changing directory. Thus, you will need to run multiple sequential commands via the PHP exec() function.

Commands:

  1. cd /var/www/html/projectfolder/js
  2. node nodefunc.js 2>&1

This is possible by adding && or ; in between the commands.

$ret = exec("cd /var/www/html/projectfolder/js; node nodefunc.js 2>&1", $out, $err);

I got it finally. It's just ignoring the NODE_PATH variable for reasons unknown :(

In the Nodejs File I had to give the absolute path of the module like this:

var request = require("/usr/lib/node_modules/request");