How to pass Parameter to spooky in nodejs

279 Views Asked by At

I'm trying to send the parametter countryCode to spookyjs function.

My question is how to do this , because when I wanna use the countryCode inside spooky.then(function) the countryCode is empty

thank you a lot

This is the call code

var greetings = require("./get_country.js");
var countryCode = "ES";
greetings.getOne("ES");

This is the function code:

var Spooky = require('spooky');
module.exports = {
  getOne: function(countryCode) {
    var init = function(error) {
      if (error) {
        e = new Error('Failed to initialize SpookyJS');
        e.details = error;
        throw e;
      }
      spooky.start('http://www.domain.com/');
        spooky.then(function() {
          this.emit('return', this.evaluate(function() {
            var raw_countries = document.querySelectorAll('#country-selector li.' + countryCode);
            return raw_countries;
          }));
       });
       spooky.run();
       },
       spooky = new Spooky({
         child: {
         transport: 'http'
       },
       casper: {
         logLevel: 'debug',
         verbose: true
       }
    }, init);
    spooky.on('error', function(error, stack) {
        console.error(error);
        if (stack) {
            console.log(stack);
        }
    });
    spooky.on('return', function(data) {
        console.log(data);
    });
}};
1

There are 1 best solutions below

0
On

You need to pass the required global variable to both spooky's then() as well as evaluate() functions to be able to access it as below

    spooky.start('example.com/');
    spooky.then([{ countryCode: countryCode }, function () {
        this.emit('return', this.evaluate(function (countryCode) {
            var raw_countries = document.querySelectorAll('#country-selector li.' + countryCode);
            return raw_countries;
        }), countryCode);
    }]);
    spooky.run();

Reference example