通过exec将variables传递给PhantomJS

我开始使用Grunt,并希望将一个variables传递给我通过exec运行的PhantomJS脚本。 我希望能够做的是通过一个URL的脚本从屏幕捕获。 任何帮助将不胜感激,谢谢!

达伦

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

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

这个脚本将枚举所有参数并写出到控制台。

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

在你的情况下,解决scheme是

咕噜

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

这是一个简单的方法来传递和select适用的参数。 非常灵活和易于维护。


使用像:

 phantomjs tests/script.js --test-id=457 --log-dir=somedir/ 

要么

 phantomjs tests/script.js --log-dir=somedir/ --test-id=457 

要么

 phantomjs tests/script.js --test-id=457 --log-dir=somedir/ 

要么

 phantomjs tests/script.js --test-id=457 

脚本:

 var system = require('system'); // process args var args = system.args; // these args will be processed var argsApplicable = ['--test-id', '--log-dir']; // populated with the valid args provided in availableArgs but like argsValid.test_id var argsValid = {}; if (args.length === 1) { console.log('Try to pass some arguments when invoking this script!'); } else { args.forEach(function(arg, i) { // skip first arg which is script name if(i != 0) { var bits = arg.split('='); //console.log(i + ': ' + arg); if(bits.length !=2) { console.log('Arguement has wrong format: '+arg); } if(argsApplicable.indexOf(bits[0]) != -1) { var argVar = bits[0].replace(/\-/g, '_'); argVar = argVar.replace(/__/, ''); argsValid[argVar] = bits[1]; } } }); } // enable below to test args //require('utils').dump(argsValid); //phantom.exit();