MAHDI
MAHDI

Reputation: 79

Send a value from PHP to Node JS for execution

Hello everyone!

I have a file called start.php and in this file I have set the value of x to 5. I have another file called check.js

In my PHP file I use shell_exec to run check.js

My question is, what should I do to make check.js check the value of x which is in start.php

Is it possible to do it this way while using shell_exec? If not what should I do?

Best regards

Upvotes: 2

Views: 2042

Answers (1)

Alex Baban
Alex Baban

Reputation: 11702

You could pass x in arguments when calling check.js

Assuming you have check.js located in a folder like this c:\apps\check.js here is some code you can try:

start.php

<?php

$x = 5;

$output = shell_exec("node.exe c:\apps\check.js x=$x");

echo "<pre>$output</pre>";

?>

c:\apps\check.js

const querystring = require('querystring');

const data = querystring.parse( process.argv[2] || '' );

const x = data.x;

console.log(x);

Node.js code is using querystring module (https://nodejs.org/api/querystring.html) for parsing x.

Update (if you need to pass more than one value)

start.php

<?php

$x = 5;
$y = 7;

$output = shell_exec("node.exe c:\apps\check.js x=$x+y=$y");

echo "<pre>$output</pre>";

?>

c:\apps\check.js

const querystring = require('querystring');

const data = querystring.parse( process.argv[2] || '', '+' );

console.log(data.x);
console.log(data.y);


I hope this helps.

Upvotes: 6

Related Questions