Passing a variable to PhantomJS via exec

时光怂恿深爱的人放手 提交于 2019-11-29 06:47:08
Cybermaxs

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

Here is an easy way to pass and pick args that are applicable. Very flexible and easy to maintain.


Use like:

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

OR

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

OR

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

OR

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

Script:

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!