简体   繁体   中英

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.

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.

Running a "program" from PHP is somewhat complicated, especially if you need it to run with 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.

I would suggest using a dependency - 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.

With symfony/process , running a node script is fairly simple, given that node is in 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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