简体   繁体   English

从PHP脚本调用节点

[英]Calling node from a PHP script

I'm trying to call a node script from a PHP script using exec : 我正在尝试使用exec从PHP脚本中调用节点脚本:

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

The nodescript.js being: nodescript.js是:

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". 但是我收到的是字符串“ foo”,而不是“ bar”。 If I run the node script from command line, I do get "foo" and "bar". 如果我从命令行运行节点脚本,则会得到“ foo”和“ bar”。 Somehow I don't receive any console output inside the function. 不知何故,我在函数内部未收到任何控制台输出。 What am I doing wrong? 我究竟做错了什么?

First of all, you cant get the output of exec command directly. 首先,您无法直接获取exec命令的输出。 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. 我在执行python脚本时遇到了这个问题。 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. 尝试在脚本中添加2>&1并将exec更改为shell_exec ,这将返回包含错误输出的字符串。 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. 我知道2>&1允许脚本将错误传递并调试输出到标准输出,因为它们会通过错误输出。 I had to do this to debug my scripts and the last line reappeared. 我必须这样做来调试脚本,然后重新出现最后一行。

PHP 5.6 is bundled with the phpdbg interactive debugger. PHP 5.6与phpdbg交互式调试器捆绑在一起。 However, the documentation URL points to an expired domain, at the moment, so, yeah. 但是, 文档URL指向当前已过期的域,是的。

Source: https://stackoverflow.com/a/36131176/370786 资料来源: https : //stackoverflow.com/a/36131176/370786

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM