mpen
mpen

Reputation: 283053

How to pass data from PHP to Node?

This is what I'm trying right now:

PHP

shell_exec('node bin/gfm.js '.escapeshellarg($code))

Node.js

console.log(process.argv[2]);

But Node only seems to be receiving the first line of $code, so it appears that escapeshellarg is not escaping newlines correctly.

How else can I do this? I'm fine using stdin if that's easier, but it looks complicated on both the PHP and Node side.

Upvotes: 2

Views: 1026

Answers (1)

mpen
mpen

Reputation: 283053

It took some fiddling, but I think I got it:

PHP

$spec = array(
    0 => array("pipe", 'r'),  
    1 => array("pipe", 'w'), 
);

$proc = proc_open('node bin/gfm.js', $spec, $pipes);
fwrite($pipes[0], $code);
fclose($pipes[0]);
$resp = stream_get_contents($pipes[1]);
fclose($pipes[1]);
proc_close($proc);

echo $resp;

Node.js

var fs = require('fs');

var size = fs.fstatSync(process.stdin.fd).size;
var buffer = size > 0 ? fs.readSync(process.stdin.fd, size)[0] : '';

console.log(buffer);

credit: Sigmund

Upvotes: 2

Related Questions