2

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

2
  • can check js take parameters? Commented Aug 9, 2018 at 20:49
  • I haven't programmed it do. I need to know how to make it to take the parameters. Commented Aug 9, 2018 at 21:53

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

5 Comments

That is great example.
THIS IS FANTASTIC!!!!!!!!!!!! But there is one problem. When I try it on CMD it works. But when I run the PHP file, it shows me a white page. Why? Thanks
Can you check if you have node.exe in your PATH? If not try to either add it or use full path to node.exe in PHP code.
I do have node.exe in my path.
OHHH. I found out why it doesn't work. In this line $output = shell_exec("node.exe c:\apps\check.js x=$x+y=$y"); the symbol of " doesn't run the code. But when I put " like ' it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.