Calling node.js script from PHP returns nothing
I suppose Apache user doesn't know what node
command is. If I'm right try to write in php file:
<full path to node> beerlist.nd
instead of
node beerlist.nd
To get full path to node run in terminal which node
parker.sikand
Recent college IT grad with a concentration in Management & Information Systems. I do coding for fun on the side. I also specialize in Cisco networking at the CCNP level.
Updated on June 18, 2022Comments
-
parker.sikand almost 2 years
What I want to do is simple in theory, but I cannot quite get it to work.
I wrote a simple node.js script that uses the
request
package to asynchronously fetch some data, parse it, and spit it out as html. I wanted to integrate this script in my client's php and apache based website which is on a shared host, and ran into some snags:- There is no mod_proxy, so I can't simply run my node script as a server and proxy through Apache
- I don't want to run node on port 80 and proxy to apache from node. It's just way too much overkill for what I need to do, and would introduce too many headaches for me. My particular shared host is known to have trouble keeping node server instances up, and I can't justify potential downtime just for this script to run.
- I tried the
node-cgi
package but it didn't work for me. I got errors about internal node methods not existing, I think this package is just out of date.
So what I have landed on is trying to simply call node from PHP. My whole
index.php
file is:<?php header("Content-Type: text/html"); exec("node beerlist.nd", $output); echo implode('', $output);
When I execute
php index.php
on the command line, I get my expected output, however, when I try to access this from the browser, I get nothing ieContent-Length: 0
. Why?I thought maybe it had to do with the async nature of my node script but it seems like the process stays alive until it finishes all the async calls. So shouldn't my php snippet send the output to the browser without any trouble? What am I missing here?
Edit: This gist of my node script is
var req = require('request') req("http://mywebsite.com", function(err, resp, body) { var output = // pull some interesting pieces out of the whole body console.log(output); });
The generation of my
output
variable is not central to the issue here. The relevant parts are that I userequest
to make an asynchronous call and useconsole.log
to output my results... maybe this is a problem? -
parker.sikand about 10 yearsAs a note, using Bluehost shared hosting, calling an unknown executable from PHP does not yield an error line, so be careful!
-
smohadjer about 7 yearsIs there a way to get full path to node in php rather than in terminal? This way I won't need to update my php file every time I upgrade nodejs or push to a production server.
-
Matias Kinnunen over 6 years@smohadjer, you could try to execute this command in PHP:
"$(which node)" beerlist.nd
. See e.g. stackoverflow.com/q/3437514/1079869 for more info.