如何通过命令行将变量作为参数传递给 CasperJS 脚本? [英] How to pass a variable as an argument to a CasperJS script through the command line?

查看:26
本文介绍了如何通过命令行将变量作为参数传递给 CasperJS 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在通过 cmd 运行的 js 文件中使用 PhantomJs、CasperJs 和 Js.

I'm using PhantomJs, CasperJs, and Js in a js file ran through the cmd.

假设我们有两个文件(test1.js 和 test2.js).这两个文件都有一个 url/site 变量,用于将测试定向到特定地址.每次环境改变或目标位置改变时,我们都需要更新这个变量.

Imagine we had two files(test1.js, and test2.js). Both files have a url/site variable that directs the test to a particular address. Everytime an environment changed or the target location changed, we would need to update this variable.

为了避免更新文件,我想通过命令行传递值,以了解在哪里测试.

To avoid having to update the files, I'd like to pass the values through the command line, as to where to test this.

有没有办法在运行文件时通过 cmd 声明字符串变量?

Is there a way to declare the string variable through the cmd as you run the file?

例如:

casperjs test.js "var site='http://google.com';"

推荐答案

文档 说你可以传递命令行参数.

The documentation says you can pass command-line parameters.

CasperJS 附带一个内置的命令行解析器PhantomJS 的一个,位于 cli 模块中;它公开传递的参数作为位置选项和命名选项

CasperJS ships with a built-in command line parser on top of PhantomJS’ one, located in the cli module; it exposes passed arguments as positional ones and named options

但是不用担心操纵cli模块解析API,一个Casper实例总是包含一个随时可用的 cli 属性,允许轻松访问所有这些参数.

But no worries for manipulating the cli module parsing API, a Casper instance always contains a ready to use cli property, allowing easy access of all these parameters.

示例代码:

var casper = require("casper").create();

casper.echo("Casper CLI passed args:");
require("utils").dump(casper.cli.args);

casper.echo("Casper CLI passed options:");
require("utils").dump(casper.cli.options);

casper.exit();

执行结果:

$ casperjs test.js arg1 arg2 arg3 --foo=bar --plop anotherarg Casper

$ casperjs test.js arg1 arg2 arg3 --foo=bar --plop anotherarg Casper

CLI passed args: [
    "arg1",
    "arg2",
    "arg3",
    "anotherarg" ]
Casper CLI passed options: {
    "casper-path": "/Users/niko/Sites/casperjs",
    "cli": true,
    "foo": "bar",
    "plop": true }

这篇关于如何通过命令行将变量作为参数传递给 CasperJS 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆