简体   繁体   English

在php中调用node.js(nightmarejs)脚本

[英]Call node.js (nightmarejs) script in php

My problem is quiet straight, i'm beginning with nodejs/nightmarejs and i need to call this js script in my php script to retrieve the answer from it. 我的问题很安静,我从nodejs / nightmarejs开始,我需要在我的php脚本中调用此js脚本以从中检索答案。

I'm using Wamp and my scripts are both in the same folder : 我正在使用Wamp,并且我的脚本都在同一文件夹中:

C:\wamp64\www\nightmare\index.php
C:\wamp64\www\nightmare\index.js

index.js : index.js:

var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true })

nightmare
  .goto('http://yahoo.com')
  .type('form[action*="/search"] [name=p]', 'nightmare github')
  .click('form[action*="/search"] [type=submit]')
  .wait('#main')
  .evaluate(function () {
    return document.querySelector('#main .searchCenterMiddle li a').href
  })
  .end()
  .then(function (result) {
    console.log(result)
  })
  .catch(function (error) {
    console.error('Search failed:', error);
  });

index.php : index.php:

<?php

    exec("index.js", $jsOutput);
    var_dump($jsOutput);

?>

I've seen in some other posts that if i use the exec() i should give the whole command line for it to run properly, something like : 我在其他一些帖子中看到,如果我使用exec()我应该给出整个命令行以使其正常运行,例如:

exec("node index.js", $jsOutput);

I figured out i had to give the whole path to nodejs maybe? 我发现我必须将整个路径都交给nodejs吗? But i didn't find any way to retrieve the path to nodejs from my current folder. 但是我没有找到任何方法从当前文件夹中检索到nodejs的路径。 If anyone have any lights, it would be appreciated. 如果有人有任何灯光,将不胜感激。 Thanks a lot 非常感谢

To search for a file in Windows you can use where command: 要在Windows中搜索文件,可以使用where命令:

<?php
    exec('where node', $nodePath);

    if ($nodePath && $nodePath[0]) {

        exec('"' . $nodePath[0] . '" index.js', $jsOutput);

        var_dump($jsOutput);
    }
    else {
        echo 'node not found.';
    }

Under Linux you can you locate , which or find commands. 在Linux下你可以找到find命令。

Well, i guess it's a common mistake. 好吧,我想这是一个常见的错误。 I forgot to reboot my computer after i installed node.js, and it's necessary to do it to apply the changes done in the windows environment variable, that way you can call to node in the commant prompt... 安装完node.js之后,我忘了重启计算机,必须这样做才能应用在Windows环境变量中所做的更改,这样您可以在命令提示符下调用node ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM