Search code examples
phpnode.jsnightmare

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


Solution

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