通过exec将变量传递给PhantomJS [英] Passing a variable to PhantomJS via exec

查看:146
本文介绍了通过exec将变量传递给PhantomJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用Grunt并希望将一个变量传递给我通过exec运行的PhantomJS脚本。我想要做的就是传递一个网址给脚本从屏幕捕获。任何帮助将不胜感激,谢谢!



达伦



咕噜脚本

  exec('phantomjs screenshot.js',
function(error,stdout,stderr){
/ / Handle output
}
);

screenshot.js

  var page = require('webpage')。create(); 
page.open('http://google.com',function(){
page.render('google.png');
phantom.exit();
});


解决方案

命令行参数可通过模块 require('system')。args (Module System )。第一个始终是脚本名称,然后是后续参数。

此脚本将枚举所有参数并写入控制台。

  var args = require('system')。args; 
if(args.length === 1){
console.log('尝试在调用此脚本时传递一些参数!');

$ b else {
args.forEach(function(arg,i){
console.log(i +':'+ arg);
});

$ / code>

在你的情况下,解决方案是

Grunt

  exec('phantomjs screenshot.js http:// www .google.fr',
函数(error,stdout,stderr){
//处理输出
}
);

screenshot.js

  var page = require('webpage')。create(); 
var address = system.args [1];
page.open(address,function(){
page.render('google.png');
phantom.exit();
});


I'm getting started with Grunt and wanting to pass a variable to a PhantomJS script I'm running via exec. What I want to be able to do is pass a url in for the script to take the screen capture from. Any help would be greatly appreciated, thanks!

Darren

Grunt script

exec('phantomjs screenshot.js',
    function (error, stdout, stderr) {
        // Handle output
    }
);

screenshot.js

var page = require('webpage').create();
page.open('http://google.com', function () {
    page.render('google.png');
    phantom.exit();
});

解决方案

Command-line arguments are accessible via module require('system').args (Module System). The first one is always the script name, which is then followed by the subsequent arguments

This script will enumerate all arguments and write out to console.

var args = require('system').args;
if (args.length === 1) {
    console.log('Try to pass some arguments when invoking this script!');
}
else {
    args.forEach(function(arg, i) {
        console.log(i + ': ' + arg);
    });
}

In your case, the solution is

Grunt

exec('phantomjs screenshot.js http://www.google.fr',
    function (error, stdout, stderr) {
        // Handle output
    }
);

screenshot.js

var page = require('webpage').create();
var address = system.args[1];
page.open(address , function () {
    page.render('google.png');
    phantom.exit();
});

这篇关于通过exec将变量传递给PhantomJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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