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 ie Content-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 use request
to make an asynchronous call and use console.log
to output my results... maybe this is a problem?
node beerlist.nd
yield a non-empty result? – Uli Köhler Feb 22 '14 at 18:58node beerlist.nd
on the command line, yes, it is non-empty. – parker.sikand Feb 22 '14 at 19:06console.log
writes to stdout after minimal formatting stackoverflow.com/questions/4976466/…... also, my string functions simply strip out white space and a few unwanted lines. The accepted answer worked for me. – parker.sikand Feb 23 '14 at 5:39console.log
also goes to stdout, but after doing other things that you don't necessarily have control over. It's also (marginally) slower due to the overhead of doing those things. Finally, usingprocess.stdout.write
makes it crystal clear to someone reading your code that you intend to output data on stdout and it's not just a debugging line (which is usually whatconsole.log
is) that got left in the code. – josh3736 Feb 24 '14 at 3:08