简体   繁体   English

从 php 文档运行 node.js 脚本并获取 output

[英]Running node.js script from php document and getting output

I am trying to run a node.js script from PHP and getting the output in the PHP.我正在尝试从 PHP 运行 node.js 脚本并在 Z2FEC392304A5C23AC138B7CZ 中获取 output

The only way I could make it work is this but it seems really dodgy.我可以使它工作的唯一方法是这样,但它似乎真的很狡猾。

public function test() {
   exec('/usr/bin/node ' . 'test.js', $o);
 
   dd($o);
}
function test() {
   return 'hello world';
}

console.log(test())

What is the best way to achieve this?实现这一目标的最佳方法是什么? I'd need to pass parameter to it too and I doubt this is the way to achieve it.我也需要将参数传递给它,我怀疑这是实现它的方法。

It probably doesn't make any difference, but I am using Laravel.它可能没有任何区别,但我使用的是 Laravel。

Running a "program" from PHP is somewhat complicated, especially if you need it to run with args.从 PHP 运行“程序”有点复杂,特别是如果您需要它与 args 一起运行。 Since arguments need to be properly escaped, you have to call escapeshellarg() to prevent problems with passing quotes, file paths including spaces and strings starting with ~ for example.由于 arguments 需要正确转义,因此您必须调用escapeshellarg()以防止传递引号、文件路径(包括空格和以~开头的字符串)出现问题。

I would suggest using a dependency - symfony/process Docs .我建议使用依赖项 - symfony/process Docs

I know that responding with a link to a dependency is frowned upon, but handling the possible arguments and/or binary output can be hard, especially on Windows and/or other non-posix systems.我知道不赞成使用指向依赖项的链接进行响应,但是处理可能的 arguments 和/或二进制 output 可能很难,尤其是在 Windows 和/或其他非 posix 系统上。

With symfony/process , running a node script is fairly simple, given that node is in PATH使用symfony/process ,运行node脚本相当简单,因为节点位于PATH

<?php

// Run the composer autoloader
require_once __DIR__ . '/vendor/autoload.php';

use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

$process = new Process(['node', 'script.js']);
$process->run();

if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();

More in-depth usage, including running multiple processes in parallel are included in the docs .文档中包含更深入的用法,包括并行运行多个进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM