简体   繁体   中英

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.

I'm using Wamp and my scripts are both in the same folder :

C:\wamp64\www\nightmare\index.php
C:\wamp64\www\nightmare\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 :

<?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("node index.js", $jsOutput);

I figured out i had to give the whole path to nodejs maybe? But i didn't find any way to retrieve the path to nodejs from my current folder. If anyone have any lights, it would be appreciated. Thanks a lot

To search for a file in Windows you can use where command:

<?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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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