将值从PHP发送到Node JS以执行

时间:2018-08-09 20:47:32

标签: php node.js apache shell-exec

大家好!

我有一个名为start.php的文件,在该文件中,我将x的值设置为5。我还有另一个名为check.js的文件

在我的PHP文件中,我使用shell_exec运行check.js

我的问题是,我该怎么做才能使check.js检查start.php中的x值

在使用shell_exec时是否可以这样做?如果没有,我该怎么办?

最诚挚的问候

1 个答案:

答案 0 :(得分:3)

调用x时可以在参数中传递check.js

假设check.js位于c:\apps\check.js这样的文件夹中,您可以尝试以下代码:

start.php

<?php

$x = 5;

$output = shell_exec("node.exe c:\apps\check.js x=$x");

echo "<pre>$output</pre>";

?>

c:\apps\check.js

const querystring = require('querystring');

const data = querystring.parse( process.argv[2] || '' );

const x = data.x;

console.log(x);

Node.js代码正在使用querystring模块(https://nodejs.org/api/querystring.html)来解析x

  

更新(如果您需要传递多个值)

start.php

<?php

$x = 5;
$y = 7;

$output = shell_exec("node.exe c:\apps\check.js x=$x+y=$y");

echo "<pre>$output</pre>";

?>

c:\apps\check.js

const querystring = require('querystring');

const data = querystring.parse( process.argv[2] || '', '+' );

console.log(data.x);
console.log(data.y);


希望对您有所帮助。