简体   繁体   English

如何在jsdom中执行外部脚本

[英]How to execute an external script in jsdom

I have a method in a products.js file like so: 我在products.js文件中有一个方法,如下所示:

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

and would like to execute it within a jsdom env callback: 并希望在jsdom env回调中执行它:

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? 我要靠近了吗?

If you want a variable to be accessible to another file, you have to export it. 如果希望变量可以被另一个文件访问,则必须将其导出。 http://nodejs.org/api/modules.html 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 我认为您应该重组代码

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. 我们要为每个页面关联一个JavaScript抓取工具,并通过通过node.js服务器提供的URL访问抓取的数据。

As suggested by Juan, the key is using node.js modules. 正如Juan所建议的那样,关键是使用node.js模块。 The bulk of the hander method is exported from product.js: 大部分hander方法是从product.js导出的:

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

and then imported in the node.js-based server instance: 然后导入到基于node.js的服务器实例中:

//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: 这将通过名称“ products.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. 那行得通。

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

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