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

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

问题描述

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

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



为了避免更新文件,我想传递值



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



例如:

  casperjs test.jsvar site ='http:// google。 com'; 


解决方案

说明您可以传递命令行参数。


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



但是不用担心操作cli模块解析API,Casper
实例总是包含准备使用 cli 属性,允许轻松
访问所有这些参数。



$ b b

示例代码:

  var casper = require(casper)。 

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




  CLI传递的参数:[
arg1,
arg2,
arg3,
anotherarg]
Casper CLI通过选项: {
casper-path:/ Users / niko / Sites / casperjs,
cli:true,
foo:bar,
plop :true}


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

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.

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

E.g.:

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

解决方案

The documentation says you can pass command-line parameters.

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

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.

Example code:

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();

Execution results:

$ 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天全站免登陆