dongpu3792 2018-08-09 12:47
浏览 212
已采纳

从PHP发送值到Node JS执行

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

  • 写回答

1条回答 默认 最新

  • douzou7012 2018-08-09 21:47
    关注

    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.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部