如何包含多个 CasperJS 脚本共有的变量和函数?

How to include variables and functions common to a number of CasperJS scripts?

假设我需要 CasperJS 向本地主机服务器报告进度步骤。我无法让用户 casper.open 发送 POST 请求,因为它可以说是 "switch" 页,并且无法正确继续其他步骤。

我通过评估浏览器内的 XMLHttpRequest() 来 ping 本地主机来回避这个问题。不理想,但它有效。

随着脚本越来越多,我宁愿将这个通用的功能移到一个模块中,也就是说,我想将一些功能移到一个单独的模块中。

我的理解是 CasperJS 不像 node.js 那样工作,所以 require() 规则不同。我该怎么做才能做到这一点?

由于 CasperJS 基于 PhantomJS,您可以使用其 module system, which is "modelled after 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
    

之后在 CasperJS 脚本中要求它:

var tools = require("tools");

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

function test(){
    console.log("This is test");
}

module.exports = {
    test: test
};