Reputation: 2555
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;
Upvotes: 1
Views: 2050
Reputation: 31919
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.
Upvotes: 0
Reputation: 846
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.
Upvotes: 6