如何包含许多CasperJS脚本常用的变量和函数?

时间:2016-01-24 02:39:21

标签: javascript web-scraping phantomjs casperjs require

假设我需要CasperJS向localhost服务器报告进度步骤。我无法使用casper.open来发送POST请求,因为它可以“切换”页面,并且无法正常继续其他步骤。

我通过评估浏览器中的XMLHttpRequest()以ping到localhost来回避这个问题。不理想,但它有效。

随着脚本数量的增长,我宁愿将这个常用功能转移到一个模块中,也就是说,我想将一些功能转移到一个单独的模块中。

这是我的理解CasperJS不像node.js那样工作require()规则是不同的。我该如何完成这项工作?

1 个答案:

答案 0 :(得分:2)

由于CasperJS基于PhantomJS,您可以使用module system,{em>"模仿CommonJS Modules 1.1"

  1. 您可以通过其路径(完整或相对)require模块文件。

    var tools = require("./tools.js");
    var tools = require("./lib/utils/tools.js");
    var tools = require("/home/scraping/project/lib/utils/tools.js");
    
  2. 或者您可以按照node.js惯例在项目文件夹中创建子文件夹node_modules/module_name,并将模块的代码放入index.js文件中。然后它会驻留在这条路径中:

    ./node_modules/tools/index.js
    
  3. 之后需要在CasperJS脚本中使用它:

    var tools = require("tools");

    模块将以这种方式导出其功能:

    function test(){
        console.log("This is test");
    }
    
    module.exports = {
        test: test
    };