6

I'm trying to call a node script from a PHP script using exec:

$output = exec("/usr/bin/node /home/user/nodescript.js");

The nodescript.js being:

var Scraper = require('google-images-scraper');

var keywords = process.argv[2];

var scraper = new Scraper({
    keyword: keywords,
    rlimit: 10, // 10 p second
});
console.log("foo");
scraper.list(10).then(function (res) {
    console.log("bar");
    console.log(res);
});
setTimeout(function () {
    process.exit(1);
}, 20000)

But what I receive is the string "foo", and not the "bar". If I run the node script from command line, I do get "foo" and "bar". Somehow I don't receive any console output inside the function. What am I doing wrong?

Amarnasan
  • 14,939
  • 5
  • 33
  • 37

3 Answers3

2

First of all, you cant get the output of exec command directly. You need to define 2nd argument as in the docs.

exec("node yourfile.js", $output); 
echo implode("\n", $output);
abeyaz
  • 3,034
  • 1
  • 16
  • 20
0

I've run into this when executing python scripts. For some reason the last line disappears. Try adding 2>&1 to your script and change exec to shell_exec which will return a string including error output. See if that helps.

$output = shell_exec("/usr/bin/node /home/user/nodescript.js 2>&1");

I know that the 2>&1 allows for the script to pass error and debugging output to the standard output since they go through a error output. I had to do this to debug my scripts and the last line reappeared.

Paul Carlton
  • 2,785
  • 2
  • 24
  • 42
  • No... still the same. I think it is more related to apache can't run the script the same way my user does. – Amarnasan Jan 20 '16 at 19:37
  • Are you getting any error output? Because that was my issue as well with python, passing errors allowed me to see permissions and directory issues so I could debug it. What also helps is setting up environment variables with `putenv` by repeating what's in your `$PATH` – Paul Carlton Jan 20 '16 at 19:46
0

PHP 5.6 is bundled with the phpdbg interactive debugger. However, the documentation URL points to an expired domain, at the moment, so, yeah.

Source: https://stackoverflow.com/a/36131176/370786

Rolf
  • 5,550
  • 5
  • 41
  • 61