8

Tôi bắt đầu với Grunt và muốn chuyển một biến sang tập lệnh PhantomJS mà tôi đang chạy qua exec. Những gì tôi muốn để có thể làm là vượt qua một url trong cho kịch bản để chụp ảnh màn hình từ. Mọi sự trợ giúp đều rất được trân trọng, xin cảm ơn!Truyền một biến cho PhantomJS qua exec

Darren

Grunt kịch bản

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

Trả lời

17

đối số dòng lệnh có thể truy cập thông qua mô-đun require('system').args (Module System). Tên đầu tiên luôn là tên kịch bản, sau đó được theo sau bởi các đối số tiếp theo

Tập lệnh này sẽ liệt kê tất cả đối số và ghi ra bàn điều khiển.

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

Trong trường hợp của bạn, giải pháp là

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

Dưới đây là một cách dễ dàng để vượt qua và chọn args có thể áp dụng. Rất linh hoạt và dễ bảo trì.


Sử dụng như:

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

HOẶC

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

HOẶC

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

HOẶC

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

Tập lệnh:

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(); 
Các vấn đề liên quan