php - 将值从 PHP 发送到 Node JS 以执行
问题描述
大家好!
我有一个名为 start.php 的文件,在这个文件中我将 x 的值设置为 5。我还有另一个名为 check.js 的文件
在我的 PHP 文件中,我使用 shell_exec 运行 check.js
我的问题是,我应该怎么做才能让 check.js 检查 start.php 中 x 的值
在使用 shell_exec 时可以这样做吗?如果不是我该怎么办?
此致
解决方案
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);
我希望这有帮助。
推荐阅读
- swift - Swift Combine:使用类似滑动窗口的功能进行收集
- php - 正则表达式以样式显示>引号
- firebase - 有 where 子句时 React Native Firebase 异步函数退出
- excel - 获取一天最后一个条目的值
- c++ - 为什么 WriteFile 不为该代码中的后续写入提前文件偏移量?
- reactjs - React Hook Form - 多重渲染
- javascript - 将 JSON 解析为 Google 图表
- machine-learning - 使用 BigQuery ML MODEL_TYPE='AUTOML_CLASSIFIER' 时出错
- python - 获取字符串中最后一个单词的长度
- youtube-data-api - Youtube API PlaylistItems 不返回 nextPageToken