node.js - 在 Node.js(或 CMD)中运行 PHP 脚本?

标签 node.js shell cmd php-7

由于某些原因需要在PHP7中运行我的NodeJS项目的一小部分。 我知道我可以创建一个内部 API,但这会增加网络依赖性。

为了解决这个问题,我发现可以这样做

php test.php

如何向此 PHP 文件提供 JSON 输入,其中数据存储在 JS 变量中不在文件中并在另一个 JS 变量中接收输出。

function runPHP(jsonString){
    ....what to write here
    ...
    return output_string;
}

Note: Please, do not suggest Query parameters as the data is too large.

最佳答案

我假设您想从 Nodejs 进程调用 php scipt,以 JSON 格式发送一些参数,然后返回一些 JSON 并进一步处理它。

PHP 脚本:

<?php
// test.php
$stdin = fopen('php://stdin', 'r');

$json = '';

while ($line = fgets($stdin)) {
    $json .= $line;
}

$decoded = \json_decode($json);

$decoded->return_message = 'Hello from PHP';

print \json_encode($decoded);

exit(0);

nodejs 脚本:

// test.js
function runPHP(jsonString) {
  const spawn = require('child_process').spawn;
  const child = spawn('php', ['test.php']);

  child.stdin.setEncoding('utf-8');
  child.stdout.pipe(process.stdout);

  child.stdin.write(jsonString + '\n');

  child.stdin.end();
}

runPHP('{"message": "hello from js"}');

这需要一些改进和错误处理......

关于node.js - 在 Node.js(或 CMD)中运行 PHP 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52243218/

相关文章:

javascript - Firebase 管理员,导入用户不起作用

file - Node.js/Express 路由到静态文件 URL

node.js - socket.io-redis 是否支持 redis 集群?

windows - 无法在cmd中使用gradle build启动命令 'npm''

node.js - 如何让 Axios 使用 FormData 发送请求?

mongodb - MongoShell : SyntaxError: missing : after property id @(shell):1:137 mongo

linux - shell脚本linux,bash : moving files according to name field-1 to the specific path in field-2 using `cut`

shell - 是否可以在命令行中指定 shell 动词?

batch-file - 从批处理中获取文件类型描述

python - 在 python 的控制台窗口上按下鼠标