从PHP发送一个值给Node JS执行
Send a value from PHP to Node JS for execution
大家好!
我有一个名为 start.php 的文件,在这个文件中我将 x 的值设置为 5。我有另一个名为 check.js
的文件
在我的 PHP 文件中,我使用 shell_exec 到 运行 check.js
我的问题是,我应该怎么做才能让 check.js 检查 start.php
中的 x 值
在使用 shell_exec 时是否可以这样做?如果不是我该怎么办?
此致
您可以在调用 check.js
时在参数中传递 x
假设您 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
.
Update (if you need to pass more than one value)
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);
希望对您有所帮助。
大家好!
我有一个名为 start.php 的文件,在这个文件中我将 x 的值设置为 5。我有另一个名为 check.js
的文件在我的 PHP 文件中,我使用 shell_exec 到 运行 check.js
我的问题是,我应该怎么做才能让 check.js 检查 start.php
中的 x 值在使用 shell_exec 时是否可以这样做?如果不是我该怎么办?
此致
您可以在调用 check.js
x
假设您 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
.
Update (if you need to pass more than one value)
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);
希望对您有所帮助。