Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling node.js script from PHP returns nothing

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:

  1. There is no mod_proxy, so I can't simply run my node script as a server and proxy through Apache
  2. 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.
  3. 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?

like image 801
parker.sikand Avatar asked Feb 22 '14 18:02

parker.sikand


1 Answers

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

like image 79
Oleg Avatar answered Oct 30 '22 20:10

Oleg