Casperjs:" TypeError:' undefined'不是一个功能"如果在另一个文件中使用evaluate()

时间:2014-12-07 09:40:50

标签: javascript casperjs

以下代码正在使用casperjs 1.1.0-beta3和phantomjs 1.9.8:

function getImage(locator, casper) {

return casper.evaluate(function(locator) {
    return Array.prototype.map.call(document.querySelectorAll(locator), function(e) {
        return e.getAttribute('src');
    });
},locator);

};    

casper.start("http://stackoverflow.com/", function () {

    var img = getImage('img[class="sponsor-tag-img"]', this);
    this.echo(img[0]);
    this.download(img[0], "logo.png");   

});

casper.run();

但是,如果我将代码拆分为两个文件并从另一个文件调用util.getImage(),则会出现以下错误:~/tmp/PhantomCSS $ casperjs test --web-security=no demo/stack.js

FAIL TypeError: 'undefined' is not a function (evaluating 'util.getImage('img[class="sponsor-tag-img"]', this)')
#    type: uncaughtError
#    file: demo/stack.js:5
#    error: 'undefined' is not a function (evaluating 'util.getImage('img[class="sponsor-tag-img"]', this)')
#           TypeError: 'undefined' is not a function (evaluating 'util.getImage('img[class="sponsor-tag-img"]', this)')
#               at demo/stack.js:5
#               at runStep (/usr/local/lib/node_modules/casperjs/modules/casper.js:1553)
#               at checkStep (/usr/local/lib/node_modules/casperjs/modules/casper.js:399)
#    stack: not provided

stack.js:

var util = require('/home/gauss/tmp/PhantomCSS/demo/util.js');

casper.start("http://stackoverflow.com/", function () {

    var img = util.getImage('img[class="sponsor-tag-img"]', this);
    this.echo(img[0]);
    this.download(img[0], "logo.png");   

});

casper.run();

util.js中:

function getImage(locator, casper) {

    return casper.evaluate(function(locator) {
        return Array.prototype.map.call(document.querySelectorAll(locator), function(e) {
            return e.getAttribute('src');
        });
    },locator);

};

如何解决?

1 个答案:

答案 0 :(得分:0)

这不是require的工作原理。它与node.js类型require非常相似。

你有两种可能性。有关详细信息,请参阅docs

module.exports

util.js中:

function getImage(locator, casper) {
    // impl
}
module.exports = getImage;

stack.js:

var getImage = require('util'); // extension can be omitted
// use getImage(locator, casper)

此类型最适合类函数或将全局对象传递给所有函数,而不是实用函数集合。一个变体是:

util.js中:

function getImage(locator, casper) {
    // impl
}
module.exports = function(casper){
    return {
        getImage: function(locator){
            return getImage(locator, casper)
        }
    };
};

stack.js:

var util = require('util')(casper); // extension can be omitted
// use util.getImage(locator)

exports

util.js中:

function getImage(locator, casper) {
    // impl
}
exports.getImage = getImage;

stack.js:

var getImage = require('util'); // extension can be omitted
// use getImage(locator, casper)

顺便说一下,您的getImage效用函数已在CasperJS中以getElementsAttribute的形式提供:

casper.getElementsAttribute(locator, "src");