简体   繁体   中英

How could one use Node.js to run JS from PHP and return a value back?

This isn't for anything serious, more so to just play around and experiment. Just not sure where I would start. Also not bound to Node.js, just figured it's the most popular server-side JS tool around.

Though if there are some major technical reasons why one shouldn't do something like this on a real site, feel free to throw them out there.

What I'm asking about is something like…

$input = $js_string_built_via_php;

if ($run_on_server)
     $output = node.js($input);
else
     $output = '<script type="text/javascript">'.$input.'</script>';

echo $output;

There are several alternatives to using node here.

Have you seen the V8js PHP extension , which integrates the V8 engine with PHP? I don't have any experience with using it myself, though.

Alternatively, similar to using node, you could install Rhino (available in the Ubuntu repos, at least from 12.04). Or another command line javascript interpreter. Then you can execute javascript from the shell:

rhino -e '<javascript code>';

So you should be able to do something like the following. You would have to use print to output data and then parse the output back in php somehow:

<?php

function execute_js($script) {
    return shell_exec('rhino -e '.escapeshellarg($script));
}

$javascript = "
    function add(a,b) {
        return a+b;
    }
    print(add(5,6));
";

$result = execute_js($javascript);

print $result;

I doubt this would be a good idea in a production application and seems like it might be quite vulnerable with a much greater attack surface. With clients being able to inject javascript code that actually gets executed on the server. It's probably very slow at load also.

A better solution 3 years later?

dnode-php would a better solution for what you want today.

There is a cool introduction here . As mentioned by the author Henri Bergius:

DNode is a remote method invocation protocol originally written for Node.js, as the name probably tells. But as the protocol itself is quite simple, just sending newline-terminated JSON packets over TCP connections, implementations have started popping up in other languages. You can talk DNode in Ruby, Perl, Python, Java, and now PHP.

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