Question

I have a method in a products.js file like so:

var handler = function(errors, window) {...}

and would like to execute it within a jsdom env callback:

jsdom.env({
    html : "http://dev.mysite.com:3000/products.html",
    scripts : [ "http://code.jquery.com/jquery.js", "page-scrapers/products.js" ],
    done : function(errors, window) {
        handler(errors, window)
        }  
});

When executed, it tells me 'handler is not defined'. Am I getting close?

Was it helpful?

Solution

Context of the problem is to scrape data from an existing web site. We want to associate a javascript scraper for each page, and access the scraped data via URLs served up via a node.js server.

As suggested by Juan, the key is using node.js modules. The bulk of the hander method is exported from product.js:

exports.handler = function(errors, window, resp) {...

and then imported in the node.js-based server instance:

//note: subdir paths must start with './' :
var products = require('./page-scrapers/products.js'); 

This creates a reference to the method by name 'products.handler', which can then be called in the request handler:

var router = new director.http.Router({
'/floop' : {
    get : funkyFunc
}
})

var funkyFunc = function() {
var resp = this.res

jsdom.env({
    html : "http://dev.mySite.com:3000/products.html",
    scripts : [ "http://code.jquery.com/jquery.js"],
    done : function(errors, window) {products.handler(errors, window, resp)}
});
}

And that works.

OTHER TIPS

If you want a variable to be accessible to another file, you have to export it. http://nodejs.org/api/modules.html

//products.js
exports.handler = function(window, error) {...}

// another.file.js
var products = require('products.js');
jsdom.env({
    html : "http://dev.mysite.com:3000/products.html",
    scripts : [ "http://code.jquery.com/jquery.js", "page-scrapers/products.js" ],
    // This can be simplified as follows 
    done : products.handler
});

This sounds like a bad idea though, why would a handler be made into a global? I think you should restructure your code

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top