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 mand line, I do get "foo" and "bar". Somehow I don't receive any console output inside the function. What am I doing wrong?
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 mand line, I do get "foo" and "bar". Somehow I don't receive any console output inside the function. What am I doing wrong?
Share Improve this question asked Jan 20, 2016 at 19:15 AmarnasanAmarnasan 15.6k7 gold badges34 silver badges38 bronze badges 1- stackoverflow./questions/49756235 – T.Todua Commented Jan 31, 2021 at 19:25
3 Answers
Reset to default 2First of all, you cant get the output of exec mand directly. You need to define 2nd argument as in the docs.
exec("node yourfile.js", $output);
echo implode("\n", $output);
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.
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./a/36131176/370786