简体   繁体   中英

Read phantomjs command line options inside script

I start PhantomJS from command-line with option (rest of them are removed):

phantomjs --debug=false script.js

W would like to read --debug flag state inside script.js:

var page = require('webpage').create();
var debug = // init boolean value depends of flag --debug from console

page.onConsoleMessage = function(msg) {
    if(debug) {
        console.log('Console:' + msg);
    }
};

// ...

Unfortunatety system.args doesn't contain command-line options.

I was looking for google and did not find any useful hints. And i know that phantomjs can not use npm modules It is desperate. phantomjs system module is not node system module, so npm package almost can not be compatible with phantomjs. Extremely frustrated, I can only write their own command line parsing parameters

Create a file commandLineArgs.js

module.exports = function (args, optionDefinitions) {
// via : https://stackoverflow.com/questions/35454087/read-phantomjs-command-line-options-inside-script
    var result = {
        args: [],
        options: {}
    };
    for (var j in optionDefinitions) {
        var def = optionDefinitions[j];
        if (def['multiple'] === true) {
            result.options[def['name']] = [];
        }
    }

    checkPoint_i:for (var i = 1; i < args.length; i++) {
        var arg = args[i];

        if (args[i].slice(0, 1) === "-") {

            var k = args[i].replace(/^-{1,2}/, '');

            for (var j in optionDefinitions) {
                var def = optionDefinitions[j];
                if (def['name'] === k || def['alias'] === k) {
                    i++;
                    if (def['multiple'] === true) {
                        result.options[def['name']].push(args[i]);
                    } else {
                        result.options[k] = args[i];
                    }
                    continue checkPoint_i;
                }
                // no def so change to args
            }

        }
        result.args.push(arg);
    }
    return result;
};

And then mark it in your code,Use it like this

var commandLineArgs = require('./node_modules/command-line-args');
var optionDefinitions = [
    {name: 'header', alias: 'H', type: String, multiple: true},
    {name: 'debug'},
];
var command = commandLineArgs(system.args, optionDefinitions);

console.log(command.options['header']); 
console.log(command.args); 

run: phantomjs yourSctipt.js --header "Host: google.com" --debug true http://www.google.com/

// output [Host: google.com]
// output [http://www.google.com/]

Hope this can help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM