8

Sto iniziando con Grunt e voglio passare una variabile a uno script PhantomJS che sto usando tramite exec. Quello che voglio essere in grado di fare è passare un url in per la sceneggiatura da cui prendere l'acquisizione dello schermo. Qualsiasi aiuto sarebbe molto apprezzato, grazie!Passare una variabile a PhantomJS tramite exec

Darren

edizione Grunt

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

risposta

17

argomenti della riga di comando sono accessibili tramite modulo require('system').args (Modulo System). Il primo è sempre il nome dello script, seguito dagli argomenti successivi

Questo script enumera tutti gli argomenti e scrive nella 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); 
    }); 
} 

Nel tuo caso, la soluzione è

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

Ecco un modo semplice per passare e prendere args che sono applicabili. Molto flessibile e facile da mantenere.


Usa come:

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

O

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

O

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

O

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