【问题标题】:Send a value from PHP to Node JS for execution将值从 PHP 发送到 Node JS 以执行
【发布时间】:2018-08-09 20:47:31
【问题描述】:

大家好!

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

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

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

在使用 shell_exec 时可以这样做吗?如果不是我该怎么办?

最好的问候

【问题讨论】:

  • 可以检查js带参数吗?
  • 我还没有编程。我需要知道如何让它接受参数。

标签: php node.js apache shell-exec


【解决方案1】:

你可以在调用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

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

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);


我希望这有帮助。

【讨论】:

  • 这是一个很好的例子。
  • 这太棒了!!!!!!!!!!!!但是有一个问题。当我在 CMD 上尝试它时,它可以工作。但是当我运行 PHP 文件时,它会显示一个白页。为什么?谢谢
  • 你能检查一下你的PATH中是否有node.exe吗?如果不尝试添加它或在 PHP 代码中使用 node.exe 的完整路径。
  • 我的路径中有 node.exe。
  • 哦。我发现了为什么它不起作用。在这一行 $output = shell_exec("node.exe c:\apps\check.js x=$x+y=$y"); " 的符号不会运行代码。但是当我输入 " like ' 时它可以工作。
猜你喜欢
  • 2019-04-05
  • 2020-04-11
  • 2015-05-18
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
相关资源
最近更新 更多